I have a list of images in my code for this component called "url". I also have a state variable called currImageIndex
. What I want to happen is every time this component is rendered, I would like to start a timer. Every second this timer runs, I would like to increment my state variable currImageIndex
. When currImageIndex 1
is greater than or equal to url
length, I would like to reset currImageIndex
to zero. The overall goal is to simulate an automatic slideshow of images by just returning <img src={url[currImageIndex]}>
. However, I am having issues with incrementing my state variable. I followed some code I found on here, but I can't figure out how to get the increment working. Here is my code.
const { url } = props;
const [currImageIndex, setCurrImageIndex] = useState(0);
console.log(url)
const increment = () => {
console.log(url.length)
console.log(currImageIndex)
if (currImageIndex 1 < url.length) {
setCurrImageIndex((oldCount) => oldCount 1)
}
else {
setCurrImageIndex(0)
}
}
useEffect(() => {
const id = setInterval(increment, 1000);
return () => clearInterval(id);
}, []);
return (
<div className={styles.container}>
<div className={styles.header}>Preview of GIF:</div>
<img src={url[currImageIndex]} alt="GIF Preview" className={styles.image} />
<div>{currImageIndex}</div>
</div>
);
When I run this with a url
of size 2, the third to last line ("{currImageIndex}") displays the 1 then 2 then 3 and so on. It does not reset ever. My console.log(url.length)
prints 2 and my console.log(currImageIndex)
prints 0. What I want to happen is currImageIndex
should be 0, 1, 0, 1, 0, 1,.... Can anyone help me understand what I am doing wrong? Thank you!
CodePudding user response:
The reason is that the callback passed on setInterval only access the currImageIndex
variable in the first render, not the new value while render so you will always get currImageIndex = 0
and pass the condition if (currImageIndex 1 < url.length)
. I update your code and make it work like your expectation: