T
TanStack12mo ago
correct-apricot

Persisting error state in react-query until successful refetch

I'm using React Query to fetch a list of users via the useQuery hook. When the fetch fails, I display an error message along with a retry button. When I call refetch, both isError and error are immediately reset to false and null. This results in the error message disappearing momentarily, which I want to avoid. Is there a way to persist the error state in React Query until the data is successfully fetched without using additional React useState to track the error manually? Ideally, I'd like to keep everything managed with react-query. Any suggestions or best practices would be greatly appreciated!
const { data, isLoading, isFetching, isError, refetch } = getUsers();

if (isError) {
return (
<div className='border border-neutral-200 py-8 px-4 rounded-md text-center'>
<div>
<Typography variant='base' as='h1' weight={500} className='text-black'>
Oh no, something went wrong!
</Typography>
<Typography variant='small' as='h1' weight={500} className='text-black'>
Sorry, we ran into an issue fetching the information. A quick retry might solve it.
</Typography>
</div>
<div className='mt-4'>
<Button impact='light' color='blue' onClick={() => refetch()} className='inline-flex px-4'>
{isFetching ? <Icon name='Loader' className='animate-spin' /> : 'Retry'}
</Button>
</div>
</div>
);
}
const { data, isLoading, isFetching, isError, refetch } = getUsers();

if (isError) {
return (
<div className='border border-neutral-200 py-8 px-4 rounded-md text-center'>
<div>
<Typography variant='base' as='h1' weight={500} className='text-black'>
Oh no, something went wrong!
</Typography>
<Typography variant='small' as='h1' weight={500} className='text-black'>
Sorry, we ran into an issue fetching the information. A quick retry might solve it.
</Typography>
</div>
<div className='mt-4'>
<Button impact='light' color='blue' onClick={() => refetch()} className='inline-flex px-4'>
{isFetching ? <Icon name='Loader' className='animate-spin' /> : 'Retry'}
</Button>
</div>
</div>
);
}
2 Replies
ambitious-aqua
ambitious-aqua11mo ago
I'm wondering the same.
equal-aqua
equal-aqua11mo ago
I once had a same question n Tkdodo replied that thats not possible. As soon as you retry the error state will be set to null and loading state to true. He said this model is based on how React's suspense and error boundaries also work

Did you find this page helpful?