Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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);
}
@daveteu

This comment has been minimized.

Copy link

@daveteu daveteu commented Oct 6, 2020

this fails when offline, doesn't load cache. How would you handle that?

@kuasha420

This comment has been minimized.

Copy link

@kuasha420 kuasha420 commented Oct 19, 2020

TypeError: setting getter-only property "data"

How come?

@derindutz

This comment has been minimized.

Copy link
Owner Author

@derindutz derindutz commented Oct 20, 2020

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

This comment has been minimized.

Copy link

@kuasha420 kuasha420 commented Oct 20, 2020

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