Handling unauthorized request in react-query

Viewed 16787

I'm having problems using react-query. Whenever the response from the server is Unauthorized, useQuery is returning flags status='success' and isError=false. The server response status is 401 and the content of the json response is { error: true, message: 'UNAUTHORIZED' }. I didn't customize react-query in any way.

I'm not using the ReactQueryConfigProvider, or passing any options in the call to customize the behaviour.

This is the call:

const { status, data, error } = useQuery(
  ["hotelsList", { token: token }],
  getHotels
);

And this is the service:

const getHotels = async ({ token }) => {
  const uri = process.env.REACT_APP_API_ENDPOINT_v2 + `/hotels`
  return (await fetch(uri, {
    method: "get",
    headers: {
      Authorization: "Bearer " + token,
      "Content-Type": "application/json"
    }
  })).json()
}

Being the token invalid, the server is responding with an 401 status code and my custom json response.

Response code from server is 401

This is the data and error objects from react-query.

Objects returned by useQuery

3 Answers

To expand on Chamsddine response, i needed to throw an error when fetch response was not ok. This enabled all the error flags on react-query.

const response = await fetch(uri, {
  method: "get",
  headers: {
    Authorization: "Bearer " + token,
    "Content-Type": "application/json"
  }
})
if (!response.ok) throw new Error(response.statusText)
return await response.json()

React-query is agnostic about your API that error is only supposed to change Is when your API doesn't respond that's when you will get an error but if the server responds with 404 or 401 etc react-query won't care because it's a valid response, react-query is only the gateway for the response it doesn't handle it in useQuery, I have made a demo here: you can see that the URL is wrong (points to a 404) and it's returning 404 it won't affect the error value but try to change the API URL to github.x for example, it will fail cause no response has been returned and the error value will change

CodeSandbox Demo

None of the solutions works with Typescript, what I did was:

 const { isLoading, error, data } = useCampaign()
  let myCustomErrorLet: any = {}
  myCustomErrorLet.data = error
  console.log(myCustomErrorLet?.data?.response);
Related