How to access cache keys outside of React component / hook in >=1.0.0-beta.13 #1424
-
In 1.0.0-beta.12, I was able to do the following: import { createCache } from "swr";
const cacheProvider = new Map();
const { cache, mutate } = createCache(cacheProvider);
const matchMutate = (matcher, data, shouldRevalidate = true) => {
const keys = [];
if (matcher instanceof RegExp) {
// `provider` is your cache implementation, for example a `Map()`
for (const k of cacheProvider.keys()) {
if (matcher.test(k)) {
keys.push(k);
}
}
} else {
keys.push(matcher);
}
const mutations = keys.map((k) => mutate(k, data, shouldRevalidate));
return Promise.all(mutations);
};
export { cache } // Elsewhere in my App.js, I do this:
import { cache } from "cache";
<SWRConfig value={{ cache, fetcher: API_FETCHER }}>
...etc
</SWRConfig> The After upgrading to import { mutate } from "swr";
const cacheProvider = new Map();
// The matchMutate function is unchanged
export { cacheProvider } import { cacheProvider } from "cache";
<SWRConfig value={{ provider: () => cacheProvider, fetcher: API_FETCHER }}>
...etc
</SWRConfig> The problem with this approach is that in my const { cache } = useSWRConfig(); ...in order to do that, I would need to add that line of code (or a hook that wraps it) into every component where I then want to invalidate some keys from and then pass the How can I create a global cache instance like I was in Thanks. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Thanks for the detailed explanation! The change in 1.0.0 that drops I think the problem is that you have to access to that const cache = new Map()
let mutate
const Wrapper = ({ children }) => {
mutate = useSWRConfig().mutate
return children
}
export { cache, mutate, Wrapper } And then use <SWRConfig value={{ provider: () => cache }}>
<Wrapper>
<App/>
</Wrapper>
</SWRConfig> Because the app can be scoped by different cache providers, fundamentally the issue is that import { mutate, SWRConfig } from 'swr'
SWRConfig.default.cache Let me know if it helps! |
Beta Was this translation helpful? Give feedback.
Thanks for the detailed explanation!
The change in 1.0.0 that drops
createCache
is mostly for concurrent safety.I think the problem is that you have to access to that
mutate
function (you still have access to the cache provider) without hooks, which is indeed a bit tricky. Maybe a solution for now is to "expose" themutate
function outside:And then use
Wrapper
insideSWRConfig
:Because the app can be scoped by different cache providers,…