reduxjs / redux-toolkit

The official, opinionated, batteries-included toolset for efficient Redux development
https://redux-toolkit.js.org
MIT License
10.54k stars 1.14k forks source link

RTK-query: Behavior of the keepUnusedDataFor #3644

Open 01-binary opened 11 months ago

01-binary commented 11 months ago

Discussed in https://github.com/reduxjs/redux-toolkit/discussions/3638

Originally posted by **01-binary** August 4, 2023 When you have pages a and b, you use the same useSomeQuery on pages a and b. not to use cache I gave option `keepUnusedDataFor: 0` on useSomeQuery. Both pages a and b use the condition `isLoading`. if isLoading is true, the loading component is shown. ``` const { isUninitialized, isFetching, currentData } = useSomeQuery( { ...., }, { refetchOnMountOrArgChange: true, }, ); const isLoading = isUninitialized || isFetching; ``` but when moving from page a to page b, page b flickers. So I ran console.log on page b. `console.log(isUninitialized, isFetching);` Three console.logs are run, the results are `true false` , `false false` , `false true` in that order. The reason why the flicker phenomenon occurs is the second result. Since the cache is not used, an API request is made again, but isUninitialized and isFetching become false just before that. UnsubscribeQueryResult is executed between the first result and the second result, and at that stage, isUninitialized does not change to true and remains false. It seems to distinguish whether or not to access a specific cache as an argument of the hook(ex: useSomeQuery), so I put in an argument such as an unused id and it worked as I expected. As another example, there is no problem when moving between page a using useSomeQuery and page b not using it. I wonder if I am using rtk-query incorrectly or if it is a bug in rtk-query. If it's a bug, I'll contribute. Thanks for reading.
MateuszGroth commented 1 month ago

I also experienced issues with refetchOnMounrOrArgChange. I would prefer the re-fetch to happen immediately along with the setting of 'isFetching' to true. When I move from page A to page B, both using the same query, and set refetchOnMountOrArgChange to true in page B's code, the useQuery hook initially returns cached data with false isFetching and setting it to true only after the first render circle, as a result of which I end up having seemingly 'fresh' data on the initial render as there is no indication (other than the last fetch timestamp), that this data is actually not up to date and is about to be re-fetched