T
TanStack4y ago
stormy-gold

Throwing error not resulting in react-query capturing 'error' state

Hello, I have a POST function using fetch like:
export const post_data = async (url, body) => {
let response = await fetch(url, {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
body: JSON.stringify(body),
});
let data = await response.json();
if (!response.ok >= 400) {
throw new Error(`${response.status} - Some error`);
}
return data;
};
export const post_data = async (url, body) => {
let response = await fetch(url, {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
body: JSON.stringify(body),
});
let data = await response.json();
if (!response.ok >= 400) {
throw new Error(`${response.status} - Some error`);
}
return data;
};
And my invocation / use of that fetch function looks like:
async function handleQuerySubmit() {

const response = await post_data(`https://${api}/query/create`, data);


}
async function handleQuerySubmit() {

const response = await post_data(`https://${api}/query/create`, data);


}
And finally wrapped with react-query useMutataion
const queryMutation = useMutation(handleQuerySubmit, {
onError: () => {
console.log("I should be getting called")
},
});
const queryMutation = useMutation(handleQuerySubmit, {
onError: () => {
console.log("I should be getting called")
},
});
However, when I throw the error in post_sentry, react-query does not execute
onError
onError
as expected. Any ideas what I am doing wrong?
3 Replies
ratty-blush
ratty-blush4y ago
Hi I think post_data should throw, not return an error The test performed before creating the error also mixes response.ok() (bool) with a comparison to error status. Unsure this is expected
stormy-gold
stormy-goldOP4y ago
hey @glabat - Thanks for responding. Both were typos on my part distilling from codebase to writeup here. Issue persists even if I throw error with simple status code Wondering if how I have composed all of this is some sort of anti-pattern? Okay resolving this. I am actually stupid and was calling the function handleQuerySubmit instead of queryMutation.mutate() . Im dumb
ratty-blush
ratty-blush4y ago
👍

Did you find this page helpful?