Skip to content

Instantly share code, notes, and snippets.

@lxsmnsyc
Last active September 3, 2021 04:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lxsmnsyc/cd248c1860619f97119d9f8881905228 to your computer and use it in GitHub Desktop.
Save lxsmnsyc/cd248c1860619f97119d9f8881905228 to your computer and use it in GitHub Desktop.
createSWRResource
interface SWROptions {
revalidateOnVisibility?: boolean;
revalidateOnNetwork?: boolean;
revalidateOnFocus?: boolean;
}
function createSWRResource<T>(
data: Resource<T>,
refetch: () => void,
options: SWROptions,
): Resource<T> {
const [state, setSignal] = createSignal(untrack(data));
createEffect(() => {
if (!data.loading && !data.error) {
setSignal(data());
}
});
let throttle;
function revalidate() {
if (throttle) {
clearTimeout(throttle);
}
throttle = setTimeout(() => {
refetch();
throttle = undefined;
}, 2000);
}
createEffect(() => {
if (options.revalidateOnVisibility ?? true) {
const onVisible = () => {
if (document.visibilityState === 'visible') {
revalidate();
}
};
window.addEventListener('visibilitychange', onVisible, false);
onCleanup(() => {
window.removeEventListener('visibilitychange', onVisible, false);
});
}
if (options.revalidateOnFocus ?? true) {
window.addEventListener('focus', revalidate, false);
onCleanup(() => {
window.removeEventListener('focus', revalidate, false);
});
}
if (options.revalidateOnNetwork ?? true) {
window.addEventListener('online', revalidate, false);
onCleanup(() => {
window.removeEventListener('online', revalidate, false);
});
}
});
return state;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment