Can we change staleTime and cacheTime via props or state change after query is mounted?
Are these example custom hooks implementation valid for v3/v4/v5?
1. Change stale time or cache time when query key changes in custom hook implementation
2. Change stale time or cache time without changing query key
3. Different custom hooks set different staleTime value on same query key
Example for 1:
Example for 2:
Example 3:
3 Replies
exotic-emerald•2y ago
whats the use case?
helpful-purpleOP•2y ago
Suppose, for example 1, when the request includes search param, the data should have zero stale time so search results are always upto date, but for other cases a larger stale time is acceptable
Other use case I think of is prefetching queries. What if I provide a shorter staleTime when calling prefetchQuery vs the main useQuery hook defines a different stale time. As prefetch is only a guess on user interaction.
My actual use case is this:
Case1 : I have a chat window with search messages functionality. The messages API response is cached using
useInfiniteQuery
with staleTime
Infinity
. Once loaded, the cache only updates via with fetchNextPage
and or fetchPreviousPage
calls or when different socket events are received (Thanks to this awesome article (https://tkdodo.eu/blog/using-web-sockets-with-react-query).
Case 2: When I search, a different API fetches the search results which contains cursor information on how to fetch the messages containing the search result. I use the cursor information from the selected result and *make it part of the query key *and and also pass the cursor as initialPageParam
for the API call from the same (Thanks to your answer here, I could build that feature: https://discord.com/channels/719702312431386674/1191643478711599155/1191643478711599155).
Doing so, my view now shows results (a page of messages) from a different query key .
When user exists search, my query key changes again and I switch back to previous state.
Now both the cases use the same custom hook which wraps basically useInfiniteQuery
.
But for the second case, I want the staleTime
to be zero instead of Infinity
Does the problem description makes sense?Discord
Discord - A New Way to Chat with Friends & Communities
Discord is the easiest way to communicate over voice, video, and text. Chat, hang out, and stay close with your friends and communities.
exotic-emerald•2y ago
you can pass staleTime in as a prop to your custom hook. If only one of them is mounted, that staleTime will be taken