Home > database >  scrollToIndex out of range: item length 0 but minimum is 1
scrollToIndex out of range: item length 0 but minimum is 1

Time:10-13

My horizontal FlatList works fine with dummy data but when i try to pass data from backend to my FlatList it returns the error scrollToIndex out of range: requested index -1 but minimum is 0.

Data is passed correctly in vertical FlatList but when i try with the horizontal one, it gives this error.

What do you think is wrong with my horizontal FlatList code?

useEffect(() => {
    const getIndex = (placeholder = 0) => {
        const index = places.findIndex(place => place.id === selectedPlaceId);
        if (index === -1) return placeholder;
        return index;
    };

    const index = getIndex();

    flatlist.current.scrollToIndex({index});

    const selectedPlace = places[index];
    const region = {
        latitude: selectedPlace.coordinate.latitude,
        longitude: selectedPlace.coordinate.longitude,
        latitudeDelta: 0.8,
        longitudeDelta: 0.8
    }

    map.current.animateToRegion(region);

}, [selectedPlaceId])


return (
    <FlatList
         ref={flatlist}
         data={trips}
         renderItem={({ item }) => <PostCarouselItem post={item} />}
         horizontal
         showsHorizontalScrollIndicator={false}
         snapToInterval={width - 70}
         snapToAlignment={"center"}
         decelerationRate={"fast"}
         viewabilityConfig={viewConfig.current}
         onViewableItemsChanged={onViewChanged.current}
         style={{ bottom: 10, left: 0, right: 0, position: "absolute", }}
         contentContainerStyle={{ marginHorizontal: cardWidth }}
         ListFooterComponent={<View style={{marginRight: (cardWidth * 2)}}/>}
    />
);

CodePudding user response:

Array.findIndex returns -1 if it does not find an element that matches the condition.

You need to check your condition and add validation for index value.

As example:

useEffect(() => {
    const getIndex = (placeholder = 0) => {
        const index = places.findIndex(place => place.id === selectedPlaceId);
        if (index === -1) return placeholder;
        return index;
    };

    const index = getIndex();

    if (index < trips.length) {
        flatlist.current.scrollToIndex({index});
    }

    const selectedPlace = places[index];
    const region = {
        latitude: selectedPlace.coordinate.latitude,
        longitude: selectedPlace.coordinate.longitude,
        latitudeDelta: 0.8,
        longitudeDelta: 0.8
    }

    map.current.animateToRegion(region);

}, [places, selectedPlaceId, trips])

  • Related