'React JS React Query's useMutation: Unable to retrieve the response from the server within the onError callback

I am working on a React JS project. I am using React query, https://react-query.tanstack.com/ to make API requests. I am now having a problem with mutation retrieving the response data from the server within the onError callback when the API throws 422 or 400 or 401, etc etc.

This is my mutation.

let [ createProductMutation, { data, error } ] = useMutation((payload) => createProduct(payload), {
    onMutate: () => {
      
    },
    onSuccess: (response) => {
      
    },
    onError: (err, variables, snapshotValue) => {
      //err is not the response from the server.
    }
  })

As you can see in the onError callback, there is no way to retrieve the response from the server.

The data and error (the one next to, createProductMutation) are not the response from the server too.

I tried using this.

  try {
       let response = await createProductMutation(data);
        // response from the API is not here too, "response"
    } catch (e) {
        // response from the API is not here too
    }

How can I retrieve the response within the onError callback?



Solution 1:[1]

To get the response you need to convert the error into json and then await the promise. See the example below with "message" being whatever your backend is returning for the response message.

onError: async (error, variables, context) => {
    const errorObj = error;
    const errorObjAsJSON = await errorObj.json();
    const { message } = errorObjAsJSON;
    console.log(message);
  },

You can obviously condense that further by

onError: async (error, variables, context) => {
        const errorObj = await error.json();
        const { message } = errorObj;
        console.log(message);
      },

Solution 2:[2]

let [ createItem ] = useMutation(payload => createItem(payload), {
  onError: (error) => {
    console.log(error.response.data);
    console.log(error.response.status);
  }
})

For me above solution worked! Inside onError, error.response should be available.

Solution 3:[3]

TLDR: make sure the function you provide to useQuery is returning a promise

example

useQuery('getAllUsersInfo', getAllUsersInfo)

make sure that getAllUsersInfo function is returning a promise.

I had this same issue happened to me because the function I provided to useQuery wasn't returning the promise so react query thought the request is successful while it was actually failing

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 INCIN
Solution 2 Bhargav Maniar
Solution 3