Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling unauthorized request in react-query

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

like image 962
Julio Truzzi Avatar asked Jul 21 '20 13:07

Julio Truzzi


1 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()
like image 59
Julio Truzzi Avatar answered Oct 10 '22 09:10

Julio Truzzi