I'm making an app using React Native and facing a problem while making a countdown timer.
I needed to use setInterval in order to implement this, but I found that setInterval will not act what I have expected.
So I used custom Hooks from this post, and here's the code:
import React, { useState, useEffect, useRef } from 'react';
function useInterval(callback, delay) {
const savedCallback = useRef();
// Remember the latest callback.
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
// Set up the interval.
useEffect(() => {
function tick() {
savedCallback.current();
}
if (delay !== null) {
let id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]);
}
After that, I made a button to make a timer to be triggered:
const [leftTime, setTime] = useState(300000);
const triggerTimer = () => {
useInterval(() => setTime(leftTime - 1), 1000);
};
return (
<>
<Text>{leftTime}</Text>
<TouchableOpacity onPress={() => triggerTimer()}
<Text>Start Countdown!</Text>
</TouchableOpacity>
</>
);
However, I got an error saying 'Invalid hook call. Hooks can only be called inside of the body of a function component.'
I already know that Hooks must be called at the very top of the function component, but is there any way to trigger a hook by pressing a button in the app?
Also, I want to stop the timer automatically and do something after that when the state 'leftTime' becomes 0.
question from:
https://stackoverflow.com/questions/65893926/how-to-trigger-a-hook-by-pressing-a-button-in-react-native 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…