1

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
Sivaprasad
  • 11
  • 2
  • this should help you https://stackoverflow.com/a/57502343/2765346 – Hristo Eftimov Jul 23 '21 at 10:04
  • Does this answer your question? [FlatList ScrollView Error on any State Change - Invariant Violation: Changing onViewableItemsChanged on the fly is not supported](https://stackoverflow.com/questions/48045696/flatlist-scrollview-error-on-any-state-change-invariant-violation-changing-on) – Hristo Eftimov Jul 23 '21 at 10:05

0 Answers0