swr: v2.0.0 - Clear cache doesn't work with swr infinite

Bug report

Clear cache example from the docs doesn’t work

Description / Observed Behavior

The cache still exists for the cache keys. Ex. a user who logged out would see data from the previous session prior to revalidation. (on another page, so it’s not about race conditions)

Expected Behavior

To be equivalent to what worked in prior versions.

Repro Steps / Code Example

I used to do in swr@2.0.0-beta.6:

import { useSWRConfig } from "swr"

const ReactComponent = () => {
  const { cache } = useSWRConfig()
  
  React.useEffect(() => {
    cache.clear()
  }, [cache]) // with some other dependencies
}

After updating to 2.0.0, I try to achieve the same result using the code snippet from the docs:

import { mutate } from "swr"

const clearCache = () => mutate(
  () => true,
  undefined,
  { revalidate: false }
)

// ...clear cache on logout
clearCache()

Additional Context

SWR version. 2.0.0

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 3
  • Comments: 15 (4 by maintainers)

Most upvoted comments

Closing, as the following works for me:

const { cache } = useSWRConfig();
for (const key of cache.keys()) cache.delete(key)

Finally I found a solution:

const { mutate, cache } = useSWRConfig();

const refresh = async () => {
    await Promise.all([...cache.keys()].map((key) => mutate(key)));
};

I found this hint in the source code: https://github.com/vercel/swr/blob/f0d80d32f7e6181b870b91fcaf5272084fbbbb45/_internal/src/utils/mutate.ts#L79

Are there any current work arounds for this? We’re using FlatLists in React Native, and when a user swipes to refresh, it just returns the previously cached data and not making the api calls to fetch latest data?

Thanks 😃

We skipped it by design since the infinite keys provided by users are function. We’re now discussing the solution to fix it

Do you know if there’s any progress on this discussion?

I’m using this way to clear all cache:

const { cache } = useSWRConfig();

const clearCache = () => [...cache.keys()].forEach((key) => cache.delete(key));

We skipped it by design since the infinite keys provided by users are function. We’re now discussing the solution to fix it

Are there any updates on the official plan to resolve this issue?

Cache clearing ability is vital for maintaining data integrity in production apps with sign-in / sign-out functionality