Skip to content

Instantly share code, notes, and snippets.

@LXSMNSYC
Last active Sep 3, 2021
Embed
What would you like to do?
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