Handling unauthorized request in react-query

Julio Truzzi picture Julio Truzzi · Jul 21, 2020 · Viewed 12.5k times · Source

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

Answer

Julio Truzzi picture Julio Truzzi · Jul 21, 2020

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()