React Query handling response status codes

react-query does not take care of the requests and it is completely agnostic of what you use to make them as long you have a Promise. From the documentation we have the following specification for the query function:

Must return a promise that will either resolves data or throws an error.

So if you need to fail on specific status codes, you should handle that in the query function.

The confusion comes because popular libraries usually take care of that for you. For example, axios and jQuery.ajax() will throw an error/reject if the HTTP status code falls out of the range of 2xx. If you use the Fetch API (like the discussion in the link you posted), the API won’t reject on HTTP error status.

Your first code snippet:

const handleFormSubmit = async (credentials) => {
    const data = await mutateLogin(credentials);

The content of data depends on the mutateLogin function implementation. If you are using axios, the promise will reject to any HTTP status code that falls out of the range of 2xx. If you use the Fetch API you need to check the status and throw the error or react-query will cache the whole response as received.

Your second code snippet:

const useMutateLogin = () => {
  return useMutation(doLogin, {
  throwOnError: true,
  onSuccess: data => // Do i have to check here again if i receive the user or 400 code

Here we have the same case as before. It depends on doLogin implementation.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top