'React Query useQuery & Axios

I'm trying to create an API function with a help of React Query and Axios. When I'm using useQuery with vanilla fetch function - it all works perfectly.

export const useGetDebts = async () => {
  const { families } = appStore.user;
  const res = useQuery("getDebts", async () => {
    const res = await fetch(`${API_URL}/api/family/${families[0]}/debts`, {
      method: "GET",
      headers: {
        Authorization: `Bearer ${appStore.token ?? ""}`,
      },
    });
    const parsedBody: DebtsResponse = await res.json();
    return parsedBody;
  });
  return res;
};

But when I switch the vanilla fetch function to Axios - I get an error status of 500 (not sure if it comes from React Query or Axios).

export const useGetDebts = async () => {
  const { families } = appStore.user;
  const res = useQuery("getDebts", async () => {
    const res = await axiosInstance.get<DebtsResponse>(`/api/family/${families[0]}/debts`);
    return res.data;
  });
  return res;
};

Thanks in advance for any explanations/suggestions.

P.s. The axiosInstance works fine with the useMutation hook. So it only makes me more confused. =(

export const useGetDebt = () => (
  useMutation(async (id: number) => {
    const { families } = appStore.user;
    const res = await axiosInstance.get<DebtResponse>(`/api/family/${families[0]}/debts/${id}`);
    return res.data;
  })
);

P.s.s. I'm working with React Native if it's somehow relevant.



Solution 1:[1]

react-query doesn't give you any 500 errors because react-query doesn't do any data fetching. It just takes the promise returned from the queryFn and manages the async state for you.

I'm not sure if the fetch code really works because it doesn't handle any errors. fetch does not transform erroneous status codes like 4xx or 5xx to a failed promise like axios does. You need to check response.ok for that:

 useQuery(['todos', todoId], async () => {
   const response = await fetch('/todos/' + todoId)
   if (!response.ok) {
     throw new Error('Network response was not ok')
   }
   return response.json()
 })

see Usage with fetch and other clients that do not throw by default.

So my best guess is that the fetch example also gives you a 500 error code, but you are not forwarding that error to react-query.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TkDodo