swr icon indicating copy to clipboard operation
swr copied to clipboard

useSWR deduped by mistake after cache clear

Open BertrandBordage opened this issue 5 months ago • 2 comments

Bug report

Description / Observed Behavior

This happens when you clear the cache, as described at the end of: https://swr.vercel.app/docs/mutation#mutate-multiple-items If a useSWR call was done shortly before that cache clear, then this call will be skipped if it happens shortly after the cache clear, and the returned data will be undefined. This issue happens only when the delay between the first call and the second call is smaller than dedupingInterval (2 s by default).

Setting dedupingInterval to 0 works around the issue, but disabling dedupes is not always desirable.

Expected Behavior

All useSWR requests called for the first time since a cache clear must run and not be deduped.

The problem comes from the fact that the documentation calls this "clear all cache data":

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

when in practice it’s not exactly a cache clear, as it does not remove any cache key, but sets them to undefined instead.

The proper solution would probably be to have an official way of clearing the cache.

Repro Steps / Code Example

Full example: https://codesandbox.io/p/sandbox/useswr-deduped-after-cache-clear-qkrwmj

https://github.com/vercel/swr/assets/1119169/a2e190e6-4070-4d78-b040-faa7e3591fc1

Additional Context

SWR version 2.2.4

BertrandBordage avatar Jan 21 '24 23:01 BertrandBordage

Ran into same issue. In my case, user logs out, clear cache (per documentation), and logs in before the dedup interval, gets no data.

wavded avatar Feb 09 '24 17:02 wavded

The SWR cache utilizes JavaScript's built-in Map object for data storage. To clear the entire cache, you can directly call the clear method on the cache object retrieved using useSWRConfig.

const { cache } = useSWRConfig();
cache.clear();

Important Note: Currently, there are no official TypeScript definitions for the clear method on the cache object. However, a pull request addressing this issue can be found here: https://github.com/vercel/swr/pull/2950

shhonarmandi avatar Apr 27 '24 07:04 shhonarmandi