I want build a Circular ProgressBar that count at 60 and then automatically stop.
But it can’t stop.
I want use React hooks and useEffect
My code here:
https://codesandbox.io/s/nostalgic-khorana-lijdyo?file=/src/App.js:0-686
But the code essence here also:
import React, { useState, useEffect } from "react";
import Circle from "./Circle";
export default function App() {
const [counter, setCounter] = useState(0);
useEffect(() => {
const intervalId = setInterval(() => {
if (counter < 60) {
setCounter((t) => t + 1);
console.log(counter);
} else {
console.log(`Why not run?`);
return () => clearInterval(intervalId);
}
return () => clearInterval(intervalId);
}, 100);
}, []);
return (
<div>
<div>
<Circle
size={250}
strokeWidth={5}
percentage={counter}
color="#229880"
/>
</div>
</div>
);
}
>Solution :
Here is my solution for this
const [counter, setCounter] = useState(0);
const counterValid = counter < 60;
useEffect(() => {
const intervalId = counterValid && setInterval(() =>
setCounter((t) => t + 1)
, 100);
return () => clearInterval(intervalId)
}, [counterValid]);
return (
<div>
<div>
<Circle
size={250}
strokeWidth={5}
percentage={counter*(100/60)}
color="#229880"
/>
</div>
</div>
We add counterValid as a dependency to useEffect to re-run the effect whenever the validity of the counter changes.
Also note that your circle expects a 1-100 value for percentage so I multiplied it by 100/60.