'type for useRef if used with setInterval, react-typescript
I am doing a simple animation in a next.js app.
let flipInterval = useRef();
const startAnimation = () => {
flipInterval.current = setInterval(() => {
setIsFlipping((prevFlipping) => !prevFlipping);
}, 10000);
};
for flipInterval.current
I am getting "Type 'Timeout' is not assignable to type 'undefined'". So i checked how to use Timeout type, I see that people are using but thats not working.
let flipInterval = useRef<typeof window.settimeout>();
I also passed number useRef<number>()
this time I am getting "Type 'Timeout' is not assignable to type 'number'"
this did not work neither
let flipInterval = useRef<typeof window.setInterval>();
Solution 1:[1]
you need to pass the proper return value type of setInterval
. for this use ReturnType
:
const flipInterval = useRef<ReturnType<typeof setInterval>>(null)
Solution 2:[2]
const intervalRef: { current: NodeJS.Timeout | null } = useRef(null);
const startAnimation = () => {
const id = setInterval(() => {
setIsFlipping((prevFlipping) => !prevFlipping);
}, 10000);
intervalRef.current = id;
};
const clear = () => {
clearInterval(intervalRef.current as NodeJS.Timeout);
};
Solution 3:[3]
If you are debouncing and need to clear a timeout null
needs to be handled
Posting as this might help others due to the title of the question.
const flipInterval:{current: NodeJS.Timeout | null} = useRef(null)
const startAnimation = () => {
flipInterval.current && clearTimeout(scrollTimeout.current);
flipInterval.current = setInterval(() => {
setIsFlipping((prevFlipping) => !prevFlipping)
}, 10000)
}
Solution 4:[4]
How i'm using
*It is preferable to set initialValue of useRef. Thats why null.
const timeout = useRef<NodeJS.Timeout | null>(null);
timeout.current = setTimeout(() => someAction()), 500);
useEffect(() => {
return () => clearTimeout(timeout.current as NodeJS.Timeout);
}, []);
Solution 5:[5]
let flipInterval = useRef<number | null>(null);
const startAnimation = () => {
flipInterval.current = window.setInterval(() => {
setIsFlipping((prevFlipping) => !prevFlipping);
}, 10000);
};
/* way of clear interval */
window.clearInterval(flipInterval.current || 0);
Solution 6:[6]
You need to use NodeJS.Timeout
type:
let flipInterval = useRef<NodeJS.Timeout>()
const startAnimation = () => {
flipInterval.current = setInterval(() => {
setIsFlipping((prevFlipping) => !prevFlipping)
}, 10000)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | buzatto |
Solution 2 | Olcay Ă–zdemir |
Solution 3 | Michael Dimmitt |
Solution 4 | mirik999 |
Solution 5 | Darwinnirad |
Solution 6 | kimbaudi |