I'm trying to make a slideshow where the user can play them in a default or random order and cycle through them by pressing a button. The problem comes when the user has chosen random mode; pressing the button still increments the currentIndex variable, but for some reason images[currentIndex] does not change.
const SlideshowScreen = (props) => {
const settings = props.route.params.settings;
const [images, setImages] = useState(settings.random ? props.route.params.images.sort((a, b) => 0.5 - Math.random()) : props.route.params.images);
const [currentIndex, setCurrentIndex] = useState(0);
useEffect(() => {
console.log('currentIndex', currentIndex, images[currentIndex]);
}, [currentIndex])
const newImage = () => {
if (currentIndex + 1 >= images.length) {
console.log('done');
}
else {
setCurrentIndex(currentIndex + 1);
}
}
return (
<View style={styles.mainContainer}>
<View style={styles.imageContainer}>
<Image
style={styles.image}
source={images[currentIndex].path} key={images[currentIndex].id} />
</View>
<TouchableOpacity onPress={() => newImage()}>
<Text>Next image</Text>
</TouchableOpacity>
</View>
)
}
On some clicks of the button this happens, and on others it doesn't. How is this happening? Any help would be great, thanks.