Reputation: 137
I want to retrieve the value of the latest useEffect, which is true or false and pass it into the curly bracket of the first useEffect, so it will stop decrementing the countdown when it goes level up or down.
const curLevel = 2;
const newTimer = curLevel * 15;
const timeRef = useRef(null);
const level = useRef(null);
const [ seconds, setSeconds ] = useState(newTimer);
// countdown
useEffect(() => {
const timer = setInterval(() => setSeconds(seconds => seconds - 1), 1000);
timeRef.current = timer;
return () => clearInterval(timer);
}, []);
useEffect(() => {
if(seconds === 0 || {pass returned value here} ) clearInterval(timeRef.current);
}, [seconds]);
// level comparison
useEffect(() => {
const storedLevel = curLevel;
level.current = storedLevel;
return () => storedLevel
}, []);
useEffect(() => {
console.log(level.current, curLevel) // outputs (2,3)
if(level.current !== curLevel) {}
// I want to get the value (which is true or false and pass it into the curly bracket of the first useEffect, so it will stop decrementing the countdown when it goes level up or down.
},[]);
Upvotes: 1
Views: 146
Reputation: 10873
You need to add that boolean property to the state and then track it in your first useEffect
:
const [isCurrentlevel, setIsCurrentLevel] = useState(false);
//...
useEffect(() => {
if (isCurrentLevel) {
const timer = setInterval(() => setSeconds(seconds => seconds - 1), 1000);
timeRef.current = timer;
return () => clearInterval(timer);
}
}, [isCurrentlevel]);
useEffect(() => {
console.log(level.current, curLevel) // outputs (2,3)
setIsCurrentLevel(level.current !== curLevel);
},[level.current, curLevel]);
Upvotes: 1