T
TanStack3y ago
passive-yellow

How can i access server error response

Server returns
return res.status(400).send({ error: "Invalid email or password." });
return res.status(400).send({ error: "Invalid email or password." });
When I print out the error in the onError call back of useMutation, or access the error from the mutation itself like myMutation.error.msg I get something like ": Request failed with status code 400" How do i get access to this info returned from the server { error: "Invalid email or password." }
3 Replies
quickest-silver
quickest-silver3y ago
entirely depends on your data fetching lib. with fetch, its probably json parse the body?
passive-yellow
passive-yellowOP3y ago
I'm using axios Where is the body coming from.
import { useMutation } from '@tanstack/react-query';

import AuthService, {
type User,
type Credentials,
} from '../services/AuthService';

const useAuth = () => {
return useMutation<User, Error, Credentials>({
mutationFn: (credentials) =>
AuthService.post({ data: credentials }).request(),
onSuccess: (data) => {
// TODO: save token in global state
console.log(data);
},
onError: (error) => {
// TODO: handle error
console.log('Callback: ', error.message);
},
});
};

export default useAuth;
import { useMutation } from '@tanstack/react-query';

import AuthService, {
type User,
type Credentials,
} from '../services/AuthService';

const useAuth = () => {
return useMutation<User, Error, Credentials>({
mutationFn: (credentials) =>
AuthService.post({ data: credentials }).request(),
onSuccess: (data) => {
// TODO: save token in global state
console.log(data);
},
onError: (error) => {
// TODO: handle error
console.log('Callback: ', error.message);
},
});
};

export default useAuth;
AuthService.post({ data: credentials }).request(), <--- this is the axios request in onSuccss I would have access to the json returned by the server but my problem is where to access the json returned in the onError in the component
const auth = useAuth();

const onSubmit = (data: FormInput) => {
auth.mutate(data);
};

return( {auth.isError && <ErrorMessage message={auth.error.message} />})
const auth = useAuth();

const onSubmit = (data: FormInput) => {
auth.mutate(data);
};

return( {auth.isError && <ErrorMessage message={auth.error.message} />})
I was hoping to get the sever response in auth.error.message.
passive-yellow
passive-yellowOP3y ago
I found a good lead here https://github.com/TanStack/query/discussions/1463 Looks to be what I want to do.
GitHub
Get error response object · TanStack query · Discussion #1463
Hi. A mutation I'm calling fails with 400, and in devtools I see the response: {"error":{"code":"INVALID_INPUT","message":"An application must have ...

Did you find this page helpful?