I'm trying to make a tinder-like clone where I want to show each 5 seconds a different user photo, I first get array of only images from matches and then with setInterval which I finally got to work inside effect I loop through images array and change active index of image, however when I console log active image, it's always the same image...
This always returns same active Index and same active image
console.log(images[activeImageIndex]);
useEffect(() => {
getImagesArray(mapStore.blurredMatches);
const interval = setInterval(() => {
if(images.length>0)
{
flipAndNextImage();
}
}, 5000);
return () => clearInterval(interval);
}, []);
const getImagesArray = (users) =>
{
let copy = [];
for(var i=0;i<users.length;i++)
{
copy.push(users[i].images[0]);
}
setImages(copy);
console.log('Setting images array',images);
};
const flipAndNextImage= () =>
{
console.log(images,'images');
if(activeImageIndex == images.length-1)
{
setActiveImageIndex(0);
console.log(images[activeImageIndex]);
}
else
{
setActiveImageIndex(activeImageIndex+1);
console.log(images[activeImageIndex]);
}
};
I believe this is because you update your activeImageIndex before logging the state