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); | |
} |
TypeError: setting getter-only property "data"
How come?
Hey! I created this in October 2019 as a proof-of-concept. There have been many updates to the SWR library since then and it seems it no longer works as intended. Hopefully it's still somewhat helpful to base a working implementation off of, but I don't plan to update or maintain it. Hope you understand!
Understandable. I just changed the line 47 with this:
result.mutate(localResult);
and it seems to be working.
Thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this fails when offline, doesn't load cache. How would you handle that?