I have a horizontal scrolling flatlist in my app. But onViewableItemsChanged keeps throwing an error. 'Changing onViewableItemsChanged on the fly is not supported.' I write the codes below. Please help me!
const flatListRef = useRef(null);
const [currentSectionIndex, setCurrentSectionIndex] = useState(0);
const onButtonPress = useCallback(() => {
if (currentSectionIndex === searchedData?.length - 1) {
// What you want to do at the end of the list.
} else if (flatListRef.current) {
// Go to the next item
flatListRef.current.scrollToIndex({
index: currentSectionIndex + 1,
});
setCurrentSectionIndex(currentSectionIndex + 1);
}
}, [currentSectionIndex, searchedData?.length]);
const onLeftButtonPress = useCallback(() => {
flatListRef.current.scrollToIndex({
index: currentSectionIndex - 1,
});
setCurrentSectionIndex(currentSectionIndex - 1);
}, [currentSectionIndex, searchedData?.length]);
const viewabilityConfig = useRef({
itemVisiblePercentThreshold: 100,
waitForInteraction: true,
minimumViewTime: 5,
})
const onViewableItemsChanged = useCallback(({ viewableItems }) => {
if (viewableItems.length >= 1) {
setCurrentSectionIndex(viewableItems[0].index);
}
}, [])
<FlatList
ref={flatListRef}
horizontal
pagingEnabled // cause snapping to items
data={data}
keyExtractor={(item,index)=>index.toString()}
renderItem={renderItem}
viewabilityConfig={viewabilityConfig.current}
onViewableItemsChanged={onViewableItemsChanged}
/>
{currentSectionIndex!==searchedData?.length-1&&!enteredString?<>
<View> //splinter
<TouchableOpacity onPress={()=>onButtonPress()}>
<Entypo name={'chevron-thin-right'} size={38} color={'#fff'}/>
</TouchableOpacity>
</View>
</>:null}
Remove onViewableItemsChanged from Flatlist write it like the below code, because on react-native: "71" newer versions doesn't support old way.