From 1b5d5d47c518144a4326bfcd22b44487fb131abd Mon Sep 17 00:00:00 2001 From: Jacob Paris Date: Mon, 16 Sep 2024 09:11:55 -0400 Subject: [PATCH] Update use-revalidator.md The original example looks like a GPT solution, the interval was never accounted for and the useEffect would just keep running immediately as soon as the revalidation completes --- docs/hooks/use-revalidator.md | 28 +++++++++++++++++++++++----- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/docs/hooks/use-revalidator.md b/docs/hooks/use-revalidator.md index b78561b9f96..4fb370b1b19 100644 --- a/docs/hooks/use-revalidator.md +++ b/docs/hooks/use-revalidator.md @@ -38,16 +38,34 @@ The state of the revalidation. Either `"idle"` or `"loading"`. Initiates a revalidation. ```tsx + function useLivePageData() { - const revalidator = useRevalidator(); - const interval = useInterval(5000); + const revalidator = useRevalidator() + + useInterval(() => { + if (revalidator.state === 'idle') { + revalidator.revalidate() + } + }, 5000) +} +function useInterval(callback: () => void, delay?: number) { useEffect(() => { - if (revalidator.state === "idle") { - revalidator.revalidate(); + if (delay === undefined) return + + let id: ReturnType + + function tick() { + callback() + id = setTimeout(tick, delay) } - }, [interval, revalidator]); + + id = setTimeout(tick, delay) + + return () => clearTimeout(id) + }, [callback, delay]) } + ``` ## Notes