lagData.ts
3 years ago
useDebounce.ts
1 year ago
useDebouncedEventHandler.ts
3 years ago
useFallbackAsInitial.ts
3 years ago
useResetPage.ts
3 years ago
useUniqueId.ts
4 years ago
lagData.ts
38 lines
| 1 | import {useRef, useEffect, useCallback} from 'react'; |
| 2 | |
| 3 | // SWR middleware for keeping the data even if key changes. |
| 4 | export default function lagData(useSWRNext) { |
| 5 | return (key, fetcher, config) => { |
| 6 | // Use a ref to store previous returned data. |
| 7 | const laggyDataRef = useRef(); |
| 8 | |
| 9 | // Actual SWR hook. |
| 10 | const swr = useSWRNext(key, fetcher, config); |
| 11 | |
| 12 | useEffect(() => { |
| 13 | // Update ref if data is not undefined. |
| 14 | if (swr.data !== undefined) { |
| 15 | laggyDataRef.current = swr.data; |
| 16 | } |
| 17 | }, [swr.data]); |
| 18 | |
| 19 | // Expose a method to clear the laggy data, if any. |
| 20 | const resetLaggy = useCallback(() => { |
| 21 | laggyDataRef.current = undefined; |
| 22 | }, []); |
| 23 | |
| 24 | // Fallback to previous data if the current data is undefined. |
| 25 | const dataOrLaggyData = swr.data === undefined ? laggyDataRef.current : swr.data; |
| 26 | |
| 27 | // Is it showing previous data? |
| 28 | const isLagging = swr.data === undefined && laggyDataRef.current !== undefined; |
| 29 | |
| 30 | // Also add a `isLagging` field to SWR. |
| 31 | return Object.assign({}, swr, { |
| 32 | data: dataOrLaggyData, |
| 33 | isLagging, |
| 34 | resetLaggy, |
| 35 | }); |
| 36 | }; |
| 37 | } |
| 38 |