T
TanStack4y ago
other-emerald

Setting error from the server in useMutation

I am using the useMutation hook to post data to the backend. I need to render the error message received from the backend. I can't seem to destructure the error message correctly. How do I set the error message to the onError prop?
export const postStuff = () => {
return useMutation(
async (token) =>
await axios({
url: foo,
method: "post",
data: { token },
}),
{
onError: (error) => {
console.log(error.response.data);
// error message received through successfully here
}
}
);
};`
export const postStuff = () => {
return useMutation(
async (token) =>
await axios({
url: foo,
method: "post",
data: { token },
}),
{
onError: (error) => {
console.log(error.response.data);
// error message received through successfully here
}
}
);
};`
const {
mutateAsync: postStuffFunc,
isError: postStuffIsError, // boolean works fine
error // I get 'Request failed with status code 400' and not my error message
} = postStuff();
const {
mutateAsync: postStuffFunc,
isError: postStuffIsError, // boolean works fine
error // I get 'Request failed with status code 400' and not my error message
} = postStuff();
1 Reply
fair-rose
fair-rose4y ago
The error in useMutation is exactly the same as the one in onError.

Did you find this page helpful?