How to immediately refetch a stale query? #2654
-
I'm wondering what is the best way to accomplish the equivalent of a My use case is that I'm fetching some data that has a known TTL (let's say its 5 minutes). Once that TTL is reached, the data cannot be used anymore and MUST be refetched before being used again.
But, this breaks down when:
I was able to implement it like this, but the use of const TTL = 5 * 60 * 1000 // 5 minutes
const queryClient = useQueryClient()
const myQuery = useQuery("my query", fetchData, {
staleTime: TTL,
})
useEffect(() => {
if( myQuery.isStale ) {
queryClient.invalidateQueries('my query')
}
}, [myQuery.isStale, queryClient]) Is there a better way to set up immediate refetching of stale data? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
I think an effect that listens to
not a super good improvement though, but hidden in a custom hook I think it's not a bad pattern at all. |
Beta Was this translation helpful? Give feedback.
-
Thanks @TkDodo! I suppose one consequence of this approach is that now the query will be refetched even when the window loses focus or the network is disconnected. |
Beta Was this translation helpful? Give feedback.
-
Thanks for the help @TkDodo! And your blog posts are great btw! |
Beta Was this translation helpful? Give feedback.
I think an effect that listens to
query.isStale
is a good approach, as observers are also informed about queries getting stale. To trim down the code a bit, you can use therefetch
function returned fromuseQuery
:not a super good improvement though, but hidden in a custom hook I think it's not a bad pattern at all.