redux-toolkit
redux-toolkit copied to clipboard
RTK Query: Controling refetch initiation of invalidated cached result
I have a query and a mutation endpoint. They use auto-invalidation using providesTags and invalidatesTags. But the problem I'm having is that the moment the mutation invalidates the cached query result, the latter gets refetched immediately. I would expect the data would get refetched on the next call to the endpoint but not sooner...
An example to illustrate the problem
I have two queries:
- a query that provides information whether a session is authenticated or not (API call can be executed regardless of auth state)
- a query that provides authenticated session information (API call only returns when session is authenticated but HTTP 401 otherwise)
Then I also have a logout mutation that invalidates both.
My app has a component close to root that renders based on authentication state and its info and does the following processing:
- makes a request to the first query getting back authentication state
- if the state is being authenticated it then (lazily) requests auth session info to add components specific to it
- if the state is returned as being anon, then it won't initiate the lazy query request and render according to anon state
This shows you that both queries still have a subscribed component and when the logout happens both queries get immediately refetched.
Question
How can I prevent the refetch of at least the second query (get auth session info) until I will actually make the request? If that cannot be done for a specific endpoint, can it me done for the whole API and all of its endpoints?
Subquestion to understand RTK query
How does RTK query know that some component is still mounted and subscribed to a specific query? How is that processed in the code (point me to the code lines so that I will understand this better).