1

I started using react-query a couple of days ago and everything seems amazing but I don't understand how I can handle errors returned from the server with their status code and error key

lets take the peace of code below as an example

const onError = (error) => {
    console.log('error occurred', error)
}
let { id } = useParams()
const { data: User, isLoading, isError, error, isRefetching, status, refetch } = useQuery(['get-user-by-id', id], getUserById(id), {
    onError
})

in this scenario when the API returns an error the onError function does not fire furthermore when i try to render a toast containing the {error} the message is Missing queryFn and when rendering {error?.message} the message is just Error

i would like to be able to get the message sent from the server with its key, ex.

if(error?.response.status === 404){
    if(error?.response?.data?.detail){
       let error = error?.response?.data?.detail
    }else if(error?.response?.data?.message){  //another error key that might return 
            let error = error?.response?.data?.message
    }// and so on...
    
}else if (error?.response?.status === 400){} // and so on...

or a key that I know my API would return depending on the status code this is especially critical for forms, while a get request could be fine with simple non-detailed error messages, a post request might hold relevant information about the error that can help the user understand it like if a name for a certain field is already taken or their is complex validation involved in the serverside, how can i handle error's in the way i explained above?

1 Answer 1

1

Your problem is, according to your code, that you are not passing a function as the query function parameter, but you are executing the function during render:

useQuery(['get-user-by-id', id], getUserById(id),

unless this was a typo, what you need is:

useQuery(['get-user-by-id', id], () => getUserById(id),

but given that you said you get Missing queryFn as error, I'm pretty sure this is it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.