Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>();
like image 235
Yilmaz Avatar asked Jan 09 '21 01:01

Yilmaz


4 Answers

 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);
  };
like image 147
Olcay Özdemir Avatar answered Oct 14 '22 13:10

Olcay Özdemir


you need to pass the proper return value type of setInterval. for this use ReturnType:

const flipInterval = useRef<ReturnType<typeof setInterval>>(null)
like image 23
buzatto Avatar answered Oct 14 '22 15:10

buzatto


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);
  }, []);
like image 33
mirik999 Avatar answered Oct 14 '22 15:10

mirik999


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)
}
like image 43
Michael Dimmitt Avatar answered Oct 14 '22 13:10

Michael Dimmitt