I was trying to build an image carousel in react native and came across the following error :
Invariant Violation: Changing onViewableItemsChanged on the fly is not supported
This error only appears on alternate reloads.
I've tried using useRef hook instead of useCallback and it solves the problem, but I don't understand why useCallback can't fix this
Code :
import React, { useState, useCallback } from 'react'
import { View, FlatList, Image, useWindowDimensions } from 'react-native'
import styles from './styles'
interface imagesProperties {
images: string[];
}
const ImageCarousal = ({ images } : imagesProperties) => {
const [activeIndex, setActiveIndex] = useState(0);
const windowWidth = useWindowDimensions().width;
const onCarousalChange = useCallback( (viewableItems) => {
if(viewableItems.changed.length>0)
setActiveIndex(viewableItems.changed[0].index);
}, [])
return (
<View style={styles.root}>
<FlatList
data={images}
renderItem={ ({ item }) => <Image style={[styles.image, { width: windowWidth-40 }]} source={{ uri : item }} /> }
horizontal
showsHorizontalScrollIndicator={false}
snapToInterval={ windowWidth-20 }
snapToAlignment={'center'}
decelerationRate={'fast'}
viewabilityConfig={{ viewAreaCoveragePercentThreshold: 50 }}
onViewableItemsChanged={onCarousalChange}
/>
<View style={styles.dotContainer}>
{ images.map( (image, index) => <View key={index} style={[styles.dot, { backgroundColor: (activeIndex == index) ? '#d1d1d1':'#fff' }]}></View> ) }
</View>
</View>
)
}
export default ImageCarousal