Calling resetQueries does not refetch with initial queryFn
There is a case where for the same query key by default I want to fetch one API, but when doing some action, refetch with some other API.
To do that I use one
useQuery hook to query and fetch the data. But on one a button click, I call queryClient.fetchQuery with the same queryKey and a different queryFn. Later I want to reset the query by calling queryClient.resetQueries to refetch again with the initial API, but the one previously used in queryClient.fetchQuery is called again.
Here's a codesandbox link: https://codesandbox.io/s/react-query-reset-to-initial-queryfn-r84n9i?file=/src/queries.ts:615-625
1. Component mounts useReactQueryData and fetches react-query data.
2. Press load devtools button - react-query-devtools is fetched and rendered.
3. Press reset button - react-query-devtools is fetched again.
Am I missing something that I expect third step should be fetching react-query ?arnassavickas
CodeSandbox
react-query reset to initial queryFn - CodeSandbox
react-query reset to initial queryFn by arnassavickas using @tanstack/react-query, @tanstack/react-query-devtools, axios, react, react-dom
3 Replies
continuing-cyan•4y ago
queryKey and queryFn is a pair that should live together. if you call fetchQuery with a different queryFn, that one is set as the function for this key.
what you want is to make the
repoName part of the queryKey
code also becomes a lot simpler that way: https://codesandbox.io/s/react-query-reset-to-initial-queryfn-forked-rn2hc6?file=/src/index.jsxTkDodo
CodeSandbox
react-query reset to initial queryFn (forked) - CodeSandbox
react-query reset to initial queryFn (forked) by TkDodo using @tanstack/react-query, @tanstack/react-query-devtools, axios, react, react-dom
continuing-cyan•4y ago
there is only one hook, and you get caching per repoName
note that i added
keepPreviousData just to avoid a flash of loading spinner when switching keys for the first time.
see also: https://tkdodo.eu/blog/practical-react-query#treat-the-query-key-like-a-dependency-arrayPractical React Query
Let me share with you the experiences I have made lately with React Query. Fetching data in React has never been this delightful...
unwilling-turquoiseOP•4y ago
I agree. In my example, this is a much cleaner solution that you provided. But I only created that to implement an example, while the case I'm working on doesn't easily allow this kind of pattern.
So I will have to simply remember not to create dynamic query functions like in my example then.