Skip to content
Advertisement

FlatList scrollToIndex out of range

I have a FlatList where I’m trying to scroll through each index of my data array every X amount of seconds. There’s only two items in my array right now but there could be more. The current code works for the first two iterations but then it does not seem to reset properly and I get the scrollToIndex out of range error: index is 2 but maximum is 1. I would think that when the currentIndex is >= data.length my if statement would setCurrentIndex back to 0 but it doesn’t seem to work. Basically what I’m trying to do is loop the items in the Flatlist automatically but each item pausing for a few seconds.

JavaScript

Advertisement

Answer

You’re getting this error because you are passing the item as data to the AdSlider component and it does not have any length property of course thus it returns undefined for data.length and that does not evaluate the expression currentIndex === data.length - 1 which it becomes currentIndex === undefined - 1 thus currentIndex will get increased by 1 without stopping and it will reach the value of 2 which is out of bounds.

There are several issues with your code.

  1. You should not have a component inside another component and especially not when using effects and state from the parent component. Remove AdSlider outside of the App component.

  2. You are passing item as data to the AdSlider and you are trying to fetch that as the data.length, which is obvious that it’s not going to work because the data is the item which is an object and not an array.

  3. You don’t need to use the effects inside the AdSlider, set just one effect inside the App and change currentIndex to be a ref instead of a state variable because you don’t need it’s changing state in order to re-render because you’re calling scrollToIndex for forcing the list to update and re-render.

Making it work using state and setTimeout

If you want to make the code wotk with currentIndex being in state (which you don’t need), you can move effects inside the App component and change data.length with ads.length and it will work.

JavaScript

Making it work using ref and setInterval

Best thing to do though, is to convert currentIndex to a be a ref and use setInterval instead of setTimeout to have a looping timer call every 5 seconds:

JavaScript

You can check a working Expo Snack here.

Advertisement