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.
JavaScript
x
47
47
1
import React, { useState, useRef } from 'react';
2
3
function Abb() {
4
let count = 0;
5
6
const [q1, setq1] = useState(false);
7
const [q2, setq2] = useState(false);
8
const [q3, setq3] = useState(false);
9
const start = Date.now();
10
count.toString();
11
setInterval(function () {
12
let eat = count % 3;
13
switch (eat) {
14
case 0:
15
setq1(true);
16
break;
17
case 1:
18
setq2(true);
19
break;
20
case 2:
21
setq3(true);
22
break;
23
default:
24
break;
25
}
26
console.log(count + q1 + q2 + q3);
27
console.log(q1);
28
console.log(q2);
29
console.log(q3);
30
count++;
31
if (count === 3) {
32
count = 0;
33
}
34
35
}, 3000);
36
37
return (
38
<>
39
<input type="radio" name="addd" id="" checked={q1} readOnly />
40
<input type="radio" name="addd" id="" checked={q2} readOnly />
41
<input type="radio" name="addd" id="" checked={q3} readOnly />
42
</>
43
);
44
}
45
46
export default Abb;
47
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 input
s checked attributes, which avoids creating 3 separate states for it.
JavaScript
1
24
24
1
import React, { useState, useEffect } from 'react';
2
3
function Abb() {
4
const [count, setCount] = useState(0);
5
6
useEffect(() => {
7
const intervalId = setInterval(() => {
8
setCount((c) => ++c % 3);
9
}, 3000);
10
11
return () => clearInterval(intervalId);
12
}, []);
13
14
return (
15
<>
16
<input type="radio" name="addd" id="" checked={count === 0} readOnly />
17
<input type="radio" name="addd" id="" checked={count === 1} readOnly />
18
<input type="radio" name="addd" id="" checked={count === 2} readOnly />
19
</>
20
);
21
}
22
23
export default Abb;
24