I have the following code for a simple count up counter:
function useInterval(callback: any, delay: any) {
const savedCallback = useRef();
savedCallback.current = callback;
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
useEffect(() => {
let id = setInterval(() => {
savedCallback.current();
}, delay);
return () => clearInterval(id);
}, [delay]);
}
useInterval(() => {
setTimer(timer + 1);
}, 1000);
While the code works fine, I am getting the following error for this line: savedCallback.current();
Cannot invoke an object which is possibly ‘undefined’.ts(2722)
(property) MutableRefObject.current: undefined
Any ideas on how this can be fixed? Thanks!
>Solution :
callback is of type any so it can be undefined and since
savedCallback.current = callback;
savedCallback.current can be undefined so when you try to invoke it typescript tells that you
Cannot invoke an object which is possibly ‘undefined’.
so what you can do is to give the same type to savedCallback and callback
I guess callback is a function:
function useInterval(callback: () => void, delay: any) {
const savedCallback = useRef<() => void>(() => {});
//...
}