| 1 |
import {useRef, useEffect} from 'react'; |
| 2 |
|
| 3 |
// use fallbackData as the initial data on component mount, instead of default data whenever there's a cache miss |
| 4 |
// adapted from https://viralganatra.com/how-to-fix-swr-to-work%20correctly-with-initialData-or-fallbackData/ |
| 5 |
|
| 6 |
export default function useFallbackAsInitial(useSWRNext) { |
| 7 |
return (key, fetcher, config) => { |
| 8 |
const hasMounted = useRef(false); |
| 9 |
|
| 10 |
useEffect(() => { |
| 11 |
hasMounted.current = true; |
| 12 |
}, []); |
| 13 |
|
| 14 |
// Actual SWR hook. |
| 15 |
const swr = useSWRNext(key, fetcher, { |
| 16 |
...config, |
| 17 |
fallbackData: hasMounted.current ? undefined : config?.fallbackData, |
| 18 |
revalidateOnMount: hasMounted.current && config?.fallbackData, |
| 19 |
}); |
| 20 |
|
| 21 |
return swr; |
| 22 |
}; |
| 23 |
} |
| 24 |
|