Last active
January 6, 2023 08:11
-
-
Save derindutz/179990f266e25306601dd53b8fbd8c6a to your computer and use it in GitHub Desktop.
useSWR with localforage as a persistent cache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import useSWR from '@zeit/swr'; | |
import localForage from 'localforage'; | |
import { ConfigInterface } from '@zeit/swr/dist/src/types'; | |
import { useState, useEffect } from 'react'; | |
export function usePersistentSWR(key: string, fn?: Function, config?: ConfigInterface) { | |
let handleSuccess; | |
if (config !== undefined && config.onSuccess !== undefined) { | |
const { onSuccess } = config; | |
handleSuccess = (data: any, key: string, config: ConfigInterface) => { | |
storeData(data, key); | |
onSuccess(data, key, config); | |
}; | |
} else { | |
handleSuccess = storeData; | |
} | |
let otherConfig; | |
if (config !== undefined) { | |
const { onSuccess, ...restOfConfig } = config; | |
otherConfig = restOfConfig; | |
} | |
const result = useSWR(key, fn, { onSuccess: handleSuccess, ...otherConfig }); | |
const [localResult, setLocalResult] = useState(undefined); | |
useEffect(() => { | |
async function getLocalResult() { | |
if (key && (result.data === undefined || result.data === null)) { | |
const localItem = await localForage.getItem<any>(key); | |
if ( | |
key && | |
(result.data === undefined || result.data === null) && | |
(localItem !== undefined && localItem !== null) | |
) { | |
setLocalResult(localItem); | |
} | |
} | |
} | |
getLocalResult(); | |
}, [key]); | |
if ( | |
(result.data === undefined || result.data === null) && | |
(localResult !== undefined && localResult !== null) | |
) { | |
result.data = localResult; | |
} | |
return result; | |
} | |
function storeData(data: any, key: string) { | |
localForage.setItem(key, data); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Understandable. I just changed the line 47 with this:
result.mutate(localResult);
and it seems to be working.
Thanks!