62

Here is render() function for my simple category list page.

Recently I added pagination for my FlatList View so when the user scrolls to the bottom, onEndReached is called in a certain point(onEndReachedThreshold value length from the bottom), and it will fetch the next categories and concatenate the categories props.

But my problem is onEndReached is called when render() is called In other words, FlatList's onEndReached is triggered before it reach the bottom.

Am I putting wrong value for onEndReachedThreshold? Do you see any problem?

return (
  <View style={{ flex:1 }}>
    <FlatList
      data={this.props.categories}
      renderItem={this._renderItem}
      keyExtractor={this._keyExtractor}
      numColumns={2}
      style={{flex: 1, flexDirection: 'row'}}
      contentContainerStyle={{justifyContent: 'center'}}
      refreshControl={
        <RefreshControl
          refreshing = {this.state.refreshing}
          onRefresh = {()=>this._onRefresh()}
        />
      }
      // curent value for debug is 0.5
      onEndReachedThreshold={0.5} // Tried 0, 0.01, 0.1, 0.7, 50, 100, 700

      onEndReached = {({distanceFromEnd})=>{ // problem
        console.log(distanceFromEnd) // 607, 878 
        console.log('reached'); // once, and if I scroll about 14% of the screen, 
                             //it prints reached AGAIN. 
        this._onEndReachedThreshold()
      }}
    />
  </View>
)

UPDATE I fetch this.props.categories data here

  componentWillMount() {
    if(this.props.token) {
      this.props.loadCategoryAll(this.props.token);
    }
  }
17
  • 4
    onEndReachedThreshold value range is 0 and 1, where 0 is the top of the scroll and 1 is the end of it. At first, I'd try adding 0.7 to it and check if it works as expected. Let me know if it helped
    – soutot
    Commented Dec 20, 2017 at 16:24
  • Thanks! But 0.7 didn't solve the problem. Still triggering onEndReached at the first time Commented Dec 20, 2017 at 16:25
  • what about having a class variable like this._mounted? Commented Dec 20, 2017 at 16:35
  • 2
    If this is the case, you can try adding some conditional rendering to render your FlatList only after your categories is filled with values. Something like this: categories.length > 0 ? <FlatList... /> : < ActivityIndicator />
    – soutot
    Commented Dec 20, 2017 at 16:44
  • 1
    You can try adding this condition inside your <View>. Something like this: <View> {categories ? <FlatList ... > : <Image ... /> } </View>. You can find more examples here: reactjs.org/docs/conditional-rendering.html Let me know if it works
    – soutot
    Commented Dec 20, 2017 at 17:02

21 Answers 21

88

Try to implement onMomentumScrollBegin on FlatList :

constructor(props) {
    super(props);
    this.onEndReachedCalledDuringMomentum = true;
}

...

<FlatList
    ...
    onEndReached={this.onEndReached.bind(this)}
    onEndReachedThreshold={0.5}
    onMomentumScrollBegin={() => { this.onEndReachedCalledDuringMomentum = false; }}
/>

and modify your onEndReached

onEndReached = ({ distanceFromEnd }) => {
    if(!this.onEndReachedCalledDuringMomentum){
        this.fetchData();
        this.onEndReachedCalledDuringMomentum = true;
    }
}
16
  • 1
    Hi! Sorry I had serious techinical issue on other problem, and now I'm back to this problem :) I tried out your solution but it just stops onEndReached behavior. Also I'm not familiar with constructor(props) syntax, can we try out with ES6 syntax? I kindda like your logic :) Commented Dec 26, 2017 at 13:30
  • 3
    Interesting. onEndReached is triggered only one time Commented Dec 27, 2017 at 8:46
  • 3
    Sorry no it doesnt. It renders only the first page Commented Dec 27, 2017 at 11:00
  • 1
    Hi @llario i can confirm it called onEndReached once even with your solution i.e. this.setState({ onEndReachedCalledDuringMomentum: true }) Commented Dec 28, 2017 at 12:27
  • 4
    Using onMomentumScrollBegin only works if you scroll gliding (ie. drag pull & let go)... It doesn't register if you drag slowly to the end (without letting go).
    – Giraldi
    Commented Jan 18, 2018 at 9:18
39

I've got it working with

<Flatlist
    ...
    onEndReached={({ distanceFromEnd }) => {
        if (distanceFromEnd < 0) return;
        ...
    }
    ...
/>
1
  • 1
    Could you explain this solution, it works for me at least. The distance count upward or downward the screen ?
    – thelonglqd
    Commented May 24, 2021 at 5:40
36

First check if the FlatList is inside a ScrollView or Content of native-base. Then take it outside of it Actually you don't need to use Content or ScrollView, as FlatList has both ListFooterComponent and ListHeaderComponent.

Though it is not recommended, if you really need to use Flatlist inside ScrollView, then take a look at this answer: https://stackoverflow.com/a/57603742/6170191

4
  • 3
    Yes, My FlatList is inside scrollview and the issue is gone after I remove it Commented Sep 10, 2019 at 9:55
  • 1
    @Nagibaba - Where can i find other recommendations and best practices for Flatlist and react native in general ? I read briefly through facebook.github.io/react-native/docs/performance but did not find any mention of not using flatList inside scroll view. But then again I haven't read through entire react native docs, so a link to a particular page would be helpful.
    – sushrut619
    Commented Oct 10, 2019 at 19:41
  • 1
    Dear @sushrut619 react native has many bottlenecks that affects performance highly. Don't read whole docs. Searching Google about react-native performance will give you a brighter look at many processes, but there are still many issues you may find in the future. Then stackoverflow and github will help you)
    – Nagibaba
    Commented Oct 14, 2019 at 12:40
  • What about a classic View? I need to put an absolute positioned element on the page to be always available. - btw, even if I put the FlatList as the top component in the screen, onEndReached is still called on first render, sometimes on second
    – jave.web
    Commented Feb 26, 2022 at 21:08
16

After hours of trying different approaches I got it to work by wrapping the Flatlist with a View of fixed height and flex:1. With this settings, I was able to get onEndReached called once and only after I scroll near the bottom. Here's my code sample:

render() {
    const {height} = Dimensions.get('window');
    return (    
        <View style={{flex:1, height:height}}>
            <FlatList
                data={this.props.trips_uniques}
                refreshing={this.props.tripsLoading}
                onRefresh={()=> this.props.getTripsWatcher()}
                onEndReached={()=>this.props.getMoreTripsWatcher()}
                onEndReachedThreshold={0.5}
                renderItem={({item}) => (
                <View style={Style.card}> 
                    ...
                    ...
                </View>
                )}
                keyExtractor={item => item.trip_id}
            />
        </View>
    )
}

My onEndReached() function just calls the API and updates my data. It doesn't do any calculations with regards to distance to bottom or threshold

3
  • Perfect solution.
    – Sandip Nag
    Commented Nov 24, 2021 at 18:32
  • If you got down here ... please check you have onEndReachedThreshold set, docs sound like it has some reasonable default, it doesn't, start with onEndReachedThreshold={0.5} ...
    – jave.web
    Commented Feb 26, 2022 at 21:18
  • Like a charm. Saved me a lot of time
    – 9 Guy
    Commented Mar 8, 2023 at 5:39
10

Most of the times, this error is caused because of an incorrect use of onEndReachedThreashold, which also depends of the number of items you are rendering (more items, more scroll size).

Try to follow this logic:

If 10 items cover your screen, and you are rendering 20 items on each scroll, then set onEndReachedThreashold to 0.8.

If 2 or 3 items cover your screen, and you are rendering 10 items on each scroll, then set onEndReachedThreashold to 0.5.

Also, use initialNumToRender = numItems. For some reason, using this FlatList prop helps to reduce the chance of multiple onEndReached calls.

Just play with onEndReachedThreashold value.


Other times, this error is produced because of nesting scroll views. Do not put your FlatList inside of a ScrollView. Instead, take use of the FlatList header and footer props.


For both solutions, I suggest to set the FlatList style and contentContainerStyle to { flexGrow: 1 }.

4

A bit late but I just ran into this issue and I fixed it by passing to my <FlatList/> the initialNumToRender prop. This prop is 10 by default so if you don't set it and your screen shows more than 10 items on the initial render, it is going to trigger onEndReached since it has passed the 10th element.

initialNumToRender should probably be the same as the amount of elements you fetch per page.

0
3

Remove every Scrollable View inside your FlatList

2

If you want to show 3 or 4 records and want to load the next data just when you reach the end. Set onEndReachedThreshold to 0 or 0.1.

2

If FlatList is on another FlatList or ScrollView the onEndReached call immediately when rendered component to resolve that problem doesn't wrap FlatList with another.

2

If you are using hooks, here you can find the hook version of @Ilario answer:

const onEndReachedCalledDuringMomentum = useRef(true)

onEndReachedHandler = ({ distanceFromEnd }) => {
    if(!onEndReachedCalledDuringMomentum.current){
        fetchData()
        onEndReachedCalledDuringMomentum.current = true
    }
}

<FlatList
    ...
    onEndReached={onEndReachedHandler}
    onEndReachedThreshold={0.7}
    onMomentumScrollBegin={() => { onEndReachedCalledDuringMomentum.current = false }}
/>

1

Maybe You can bypass this FlatList bug by incrementing your page before doing async call, and then you will fetch data on every onEndReached fiers and not get errors about duplicate keys

1

(as of NOV19)

  1. Keep flatlist as the only component inside of a single view
  2. Set style of that single view from dimensions like
    {{flex: 1, height: Dimensions.get('window').height}}
1

Since I haven't specifically seen this case here: If you render FlatList with an empty data source and add onEndReached to it, it will fire the onEndReached no matter the Threshold.

It seems it then disables the onEndReached completely as a safety measure even if there are items added to the data source later on.

My fix was to not render the FlatList with an empty data set, which I probably should've done to start with.

1

You can use the onScroll prop for determining when the scroller reaches a certain number of pixels from the bottom of the list

onScroll={({ nativeEvent }) => {
    const { contentOffset, contentSize, layoutMeasurement } = nativeEvent;
    const numberOfPixelsFromBottomThreshold = 100;
    const isNearBottom = contentOffset.y + layoutMeasurement.height >= contentSize.height - numberOfPixelsFromBottomThreshold
    if (isNearBottom) {
        console.log('reached 100 pixels from the bottom of scrollview')
        console.log('run your custom onEndReached logic here')
        fetchMore?.(); // I usually fetchMore when end is reached
    }
}}

This method works universally for:

  • ScrollView
  • FlatList
  • FlashList
  • SectionList
  • etc.
1
  • the best solution there is! forget about onEndReach/etc madness - really really bad. Commented Jun 4 at 19:29
0

I have a <FlatList> (from react-native) inside an <Overlay> (from react-native-elements.) I have the problem of onEndReached being executed as soon as the component is rendered for the 1st time and before the user does anything.

The problem was resolved by using <Modal> (from react-native), instead of <Overlay>.

0

This simple solution worked for me. Note the "refreshing" state is controlled by an async API call in a useEffect hook to retrieve data for the FlatList.

const onEndReachedHandler = () => {
    if (!refreshing) ...
}

<FlatList
    ...
    data={mydata}
    onEndReached={onEndReachedHandler}
    onEndReachedThreshold={0.7}
    refreshing={refreshing}
/>
0

I struggled around the whole day but the issue that I was getting is, I am using FlatList inside ScrollView. So, Remove Scrollview & then use Flatlist independently. This will solve my problem.

0

From my experience, you can simply utilize onEndReachedThreshold props in your FlatList or SectionList and pass a very very small number like 0.001 to it.

onEndReachedThreshold={0.001}

According to docs for FlatList, onEndReachedThreshold is units of length from the bottom in list items.

How far from the end (in units of visible length of the list) the bottom edge of the list must be from the end of the content to trigger the onEndReached callback. For example, a value of 0.5 will trigger onEndReached when the end of the content is within half the visible length of the list.

Thus, a very small value like 0.001 helps you to make sure that onEndReached is only gonna be called when the end of the content is within the very end of the visible length of the list.

Hope this helps :) Sorry for bad English.

0

The solution is simpler than anyone would think.

Just add an !isLoading condition for fetch calling. It works for me:

 onEndReached={() => {
      if (!isLoading) {
        fetchProducts();
      }
 }}

And the full code with ScrollView and FlatList:

<ScrollView
          horizontal={true}
          showsVerticalScrollIndicator={false}
          showsHorizontalScrollIndicator={false}
          style={styles.mainContainer}>
          <FlatList
            ListHeaderComponent={TableHeader}
            data={displayedProducts}
            renderItem={(item: ListRenderItemInfo<IProduct>) => TableRow(item, showDeleteModal)}
            keyExtractor={keyExtractor}
            ListFooterComponent={<Loading loadingText={'Loading products...'} />}
            onEndReached={() => {
              if (!isLoading) {
                fetchProducts();
              }
            }}
            onEndReachedThreshold={0.8}
            stickyHeaderIndices={[0]}
          />
</ScrollView>
0

For me (react native web in this case) it was to set a specific height directly on the flatlist style

            <FlatList
                style={{ height: windowDimensions.height }}
            // ...

Afterwards, onScroll and onEndReached worked correctly

-6

I have solved it with using debounce from lodash. Firstly, I import debounce from 'lodash.debounce'. Then I use debounce for load more function with 500 ms interval

<Flatlist onEndReached = {debounce(this._onLoadMore, 500)} />

2
  • Why do we want to implement with lodash, when the flatlist has all the functions defined? Why is react native not fixing these simple issues.
    – buddhiv
    Commented Mar 29, 2019 at 1:48
  • though I'm a fan of debounce, this solution does not work. The list will simply invoke the callback after the debounce interval. We need an onEndReach that only runs when the user reaches the end of the list. Commented Jun 22, 2019 at 4:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.