Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 256
Vladimir Greenberg Avatar asked Sep 09 '26 13:09

Vladimir Greenberg


1 Answers

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.

like image 117
TkDodo Avatar answered Sep 12 '26 03:09

TkDodo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!