I am trying to switch between input radio button checked every 3 second in Next.js, and it is switching from case0 to case1 and case1 to case2 but not case2 to case0. I have intermediate level of knowledge in React and Next.js.
import React, { useState, useRef } from 'react';
function Abb() {
let count = 0;
const [q1, setq1] = useState(false);
const [q2, setq2] = useState(false);
const [q3, setq3] = useState(false);
const start = Date.now();
count.toString();
setInterval(function () {
let eat = count % 3;
switch (eat) {
case 0:
setq1(true);
break;
case 1:
setq2(true);
break;
case 2:
setq3(true);
break;
default:
break;
}
console.log(count + q1 + q2 + q3);
console.log(q1);
console.log(q2);
console.log(q3);
count++;
if (count === 3) {
count = 0;
}
}, 3000);
return (
<>
<input type="radio" name="addd" id="" checked={q1} readOnly />
<input type="radio" name="addd" id="" checked={q2} readOnly />
<input type="radio" name="addd" id="" checked={q3} readOnly />
</>
);
}
export default Abb;
Advertisement
Answer
As @Phil mentioned in his answer, you should wrap the setInterval logic inside a useEffect to avoid creating a new setInterval every time the component re-renders. I would also suggest you move the count variable to state and use that directly to update the inputs checked attributes, which avoids creating 3 separate states for it.
import React, { useState, useEffect } from 'react';
function Abb() {
const [count, setCount] = useState(0);
useEffect(() => {
const intervalId = setInterval(() => {
setCount((c) => ++c % 3);
}, 3000);
return () => clearInterval(intervalId);
}, []);
return (
<>
<input type="radio" name="addd" id="" checked={count === 0} readOnly />
<input type="radio" name="addd" id="" checked={count === 1} readOnly />
<input type="radio" name="addd" id="" checked={count === 2} readOnly />
</>
);
}
export default Abb;