-
Just wondering if there is a way to stop useInterval once it starts. I tried the abort controller but that didn't appear to do the trick. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Not sure if it's a egregious use but looking at the source it looks like if interval is falsy it will bail out of the effect. https://github.com/hazae41/xswr/blob/master/src/mods/react/hooks/blocks/use-interval.ts#L16 useInterval params require a number but if I cheat and make the optional number (as number) it will stop the interval.
If stopping an interval is something that is reasonable I would be open to helping figure out a more ergonomic way to do it. |
Beta Was this translation helpful? Give feedback.
-
You can achieve this by using a variable export function useInterval<K, D, F>(query: Query<K, D, F>, interval: number, active: boolean) {
const { ready, fetch } = query
useEffect(() => {
if (!ready)
return
if (!interval)
return
if (!active)
return
const f = () => fetch().then(r => r.ignore())
const i = setInterval(f, interval)
return () => clearInterval(i)
}, [ready, fetch, interval, active])
} Or by simply setting the interval value to Put the variable in a const aborter = useRef(new AbortController())
const [interval, setInterval] = useState(1000)
useEffect(() => {
const onAbort = () => setInterval(0)
aborter.current.signal.addEventListener("abort", onAbort, { passive: true })
return () => aborter.current.signal.removeEventListener("abort", onAbort)
}, [])
const query = useQuery(...)
useInterval(query, interval)
return <button onClick={aborter.current.abort}>
Abort
</button> |
Beta Was this translation helpful? Give feedback.
You can achieve this by using a variable
Or by simply setting the interval value to
0
Put the variable in a
useState
, and then use theabort
event of the AbortSignal to dosetState(false)