T
TanStack•2y ago
genetic-orange

Handling HTTP errors using Fetch with useQuery

First, new to react. New to react-query. I have a POST API where the server is returning a 422. And while checking to see if the response is okay using fetch(), i'm struggling to how to pass the error back to useQuery, because if i just pass the response.json, useQuery obviously isn't going to see the error. // my .tsx file const { data: thisData, status: thisStatus, error: thisError } = useQuery({ enabled: ready, refetchOnWindowFocus: false, queryKey: ['thisData'], throwOnError: true, retry: false, queryFn: async () => { const res = await api.soSomething(props) return res.data } }) // ApiClass.ts export const MyApi = { doSomething: async function( props: MyType) { let jsonBody = JSON.stringify({ this: props.this, that: props.that, theOther: props.theOther, }) let requestOptions = { method: 'POST', headers: headers, body: jsonBody } const response = await fetch(URL + "/doSomething", requestOptions) if( !response.ok ) { console.log(ERROR: POST /doSomething .. ${response.status} , ${response.statusText}) throw new Error(response.statusText) } return response.json() } } causes ReactRouter to throw an error screen versus just bubbling the error up so i can handle it.
3 Replies
unwilling-turquoise
unwilling-turquoise•2y ago
Look up react router error handling 🙂
genetic-orange
genetic-orangeOP•2y ago
I don't want to display an error page. i want to display the error message from the http response inline on the page or am i missing something?
unwilling-turquoise
unwilling-turquoise•2y ago
Then don’t throwOnError

Did you find this page helpful?