React native infinite scroll with flatlist

Viewed 29441

I followed this tutorial https://www.youtube.com/watch?v=rY0braBBlgw When I scroll down it sends the request then it gets stuck in a loop and just requests and requests. I think this is a problem with the scrollview in the listview.

3 Answers

This works for me:

     <FlatList
          data={this.state.storesList}
          renderItem={({ item, index }) => renderItem(item, index)}
          keyExtractor={(item, index) => item.id.toString()}
          onEndReached={this.fetchMore}
          onEndReachedThreshold={0.1}
          ListFooterComponent={this.renderFooter}
          refreshing={this.state.refreshing}
        />


renderFooter = () => {
    if (this.state.refreshing) {
      return <ActivityIndicator size="large" />;
    } else {
      return null;
    }
  };


  fetchMore = () => {
    if (this.state.refreshing){
      return null;
    }
    this.setState(
      (prevState) => {
        return { refreshing: true, pageNum: prevState.pageNum + 1 };
      },
      () => {
        this.sendAPIRequest(null , true);
      }
    );
  };

The reason I used the following in the fetchMore function:

if (this.state.refreshing){
      return null;
    }

Is because when you setState to the pageNum it calls the render() function and then the fetchMore called again. This is written to prevent it. In addition, I set:

refreshing: false

after the sendAPIRequest is done. Pay attention about onEndReachedThreshold in FlatList:

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.

Meaning in my example (0.1) means: when you reach 10% of items from the bottom, the fetchMore callback is called. In my example, I have 10 items in the list, so when the last item is visible, fetchMore is called.

Related