Skip to content

Instantly share code, notes, and snippets.

@derindutz
Last active January 6, 2023 08:11
Show Gist options
  • Save derindutz/179990f266e25306601dd53b8fbd8c6a to your computer and use it in GitHub Desktop.
Save derindutz/179990f266e25306601dd53b8fbd8c6a to your computer and use it in GitHub Desktop.
useSWR with localforage as a persistent cache
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);
}
@derindutz
Copy link
Author

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!

@kuasha420
Copy link

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