I am a beginner using useEffect in React to update the index state of an array on an interval. I want the index to increase by 1 every five seconds, and when it reaches the end of the array loop back to 0.
I put an 'if' statement to check for this within my useEffect function, but it doesn't seem to be firing. When the array reaches the end, my console shows an error reading from an undefined index.
const [idx, setIdx] = useState(0);
useEffect(() => {
const interval = setInterval(() => setIdx((previousValue) => previousValue
+1), 5000);
if(idx > testimonials.length-1) { setIdx(0)};
return () => {
clearInterval(interval);
};
}, []);
Can anyone see what I'm doing wrong?