redux-toolkit icon indicating copy to clipboard operation
redux-toolkit copied to clipboard

RTK-query: Behavior of the keepUnusedDataFor

Open 01-binary opened this issue 2 years ago • 1 comments

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.

01-binary avatar Aug 07 '23 10:08 01-binary