Replies: 1 comment
-
I wrote a custom middleware to do this import { useRef } from 'react';
import { serialize, useSWRConfig, type Middleware, type SWRHook } from 'swr/_internal';
/**
* Load data once on page load
*/
export const loadOnce: Middleware = (useSWRNext: SWRHook) => (key, fetcher, config) => {
const loadedRef = useRef<Set<string>>(new Set());
const cache = useSWRConfig().cache;
if (!fetcher) throw new Error('no fetcher provided');
const k = serialize(key)?.[0];
const data = cache.get(k)?.data as ReturnType<typeof fetcher>;
const hasLoaded = data && loadedRef.current.has(k);
if (cache.get(k)?.data) loadedRef.current.add(k);
return useSWRNext(key, hasLoaded ? () => data : fetcher, config);
}; |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Is there a way to trigger a revalidation once on page load?
onMount: true
will trigger if I leave the route and re-enter or the component unmounts/remounts, this is not what I am looking for, I want it to trigger the fetch request once on "page" load.useSWRImmutable
will cache indefinitely and not revalidate on page loadBeta Was this translation helpful? Give feedback.
All reactions