Using cached data after a request has failed #5780
-
Hi I'm using react-query with react native and I'm in a situation when I would like to use the cached data when a request has failed. I'm have been trying to do it, by without success so far. Let's say I make request a get the data and it's cached, then, after the data is stale, I make another request, but it fails. The situation is that I'm always getting data undefined and the error object with the request fails details. I'm wondering if there's any to use the cached data when the request fails. This similar to my implementation. import {
QueryClient,
QueryClientProvider,
useQuery,
} from '@tanstack/react-query'
const queryClient = new QueryClient()
export default function App() {
return (
<QueryClientProvider client={queryClient}>
<Example />
</QueryClientProvider>
)
}
function Example() {
const { isLoading, error, data } = useQuery({
staleTime: 24 * 60 * 60 * 1000,
cacheTime:'Infinity',
queryKey: ['data'],
queryFn: () =>
fetch('https://some-enedpoint').then(
(res) => res.json(),
),
})
return (
<View>
<Text>{data.name}</Text>
</view>
)
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
React Query will not throw away cached data. If a background refetch fails, your Query should be in the following state:
One thing I'm seeing is that you are using |
Beta Was this translation helpful? Give feedback.
React Query will not throw away cached data. If a background refetch fails, your Query should be in the following state:
One thing I'm seeing is that you are using
fetch
, but you're not handling errors in a way that Promises are rejected when the fetch returns 4xx or 5xx responses. This is a common gotcha: