Created
August 28, 2021 16:11
-
-
Save shuding/915d6844db74e131ece951a2eff0f320 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { unstable_serialize, useSWRConfig, SWRConfig } from 'swr' | |
import { useEffect } from 'react' | |
const counter = {} | |
const gc = useSWRNext => (key, fetcher, config) => { | |
const { cache } = useSWRConfig() | |
const serializedKey = unstable_serialize(key) | |
useEffect(() => { | |
counter[serializedKey] = (counter[serializedKey] || 0) + 1 | |
return () => { | |
counter[serializedKey]-- | |
if (!counter[serializedKey]) { | |
cache.delete(serializedKey) | |
} | |
} | |
}, [serializedKey]) | |
return useSWRNext(key, fetcher, config) | |
} | |
// ... | |
<SWRConfig value={{ use: [gc] }}> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If I understand correctly, you can access the cache as
config.cache
, instead of needing to calluseSWRConfig
?