Last active
September 3, 2021 04:34
-
-
Save lxsmnsyc/cd248c1860619f97119d9f8881905228 to your computer and use it in GitHub Desktop.
createSWRResource
This file contains hidden or 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
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