I use this code:
const clearTimer = (e: any) => {
setTimer(<div></div>);
if (Ref.current) clearInterval(Ref.current);
startTimer(e);
const id = setInterval(() => {
startTimer(e);
}, 1000)
Ref.current = id;
}
For Ref.current = id;
I get this error:
(property) MutableRefObject<null>.current: null
Type 'Timer' is not assignable to type 'null'.
And these lines not solved my problem:
Ref.current = id.toString();
Ref.current = id ?? '';
When using useRef
with Typescript, you should provide a generic argument to specify what is the expected type of the held value.
In your case:
// The `current` value is expected to be a `Timer`, and is initialized to `null`
const Ref = useRef<Timer>(null);
Then Ref.current
can be assigned to the result of setInterval
.
See this article for more info: https://linguinecode.com/post/how-to-use-react-useref-with-typescript
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments