Skip to content

Instantly share code, notes, and snippets.

@shuding
Created August 28, 2021 16:11
Show Gist options
  • Save shuding/915d6844db74e131ece951a2eff0f320 to your computer and use it in GitHub Desktop.
Save shuding/915d6844db74e131ece951a2eff0f320 to your computer and use it in GitHub Desktop.
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] }}>
@joshkel
Copy link

joshkel commented May 22, 2023

If I understand correctly, you can access the cache as config.cache, instead of needing to call useSWRConfig?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment