React Native FlatList load more when we get to the bottom of the list

Mahdi Bashirpour picture Mahdi Bashirpour · Jul 10, 2018 · Viewed 10.3k times · Source

How to make load more with FlatList of React Native (Not infinite)

I've done this, but unfortunately it loads as infinitely.

This is my code snippet

<FlatList
    data={this.props.data}
    renderItem={({ item, separators }) => (
        <TouchableHighlight
            onPress={() => this._onPress(item)}
            onShowUnderlay={separators.highlight}
            onHideUnderlay={separators.unhighlight}
        >
            <Text> {item.title} </Text>
        </TouchableHighlight>
    )}
    keyExtractor={item => item.id}
    ListFooterComponent={this.renderFooter}
    onEndReached={this.props.handleLoadMore}
    onEndThreshold={0}
/>

And my handleLoadMore

handleLoadMore = () => {
    console.log("test"); // <---- this line run infinitely
    fetch(url, {
        method: "POST",
        headers: {
            Accept: "application/json",
            "Content-Type": "application/json"
        },
        body: JSON.stringify(filters)
    })
        .then(response => response.json())
        .then(responseJson => {
            this.setState({
                itemData: [
                    ...this.state.itemData,
                    ...responseJson.estate_list
                ],
                itemPage: this.state.itemPage + 1
            });
        })
        .catch(error => {
            console.error(error);
        });
};

Answer

Nikolay Tomitov picture Nikolay Tomitov · Jul 10, 2018

There is issue when loading data in FlatList and your onEndReached handler will be called when the view is re-rendered. Try setting a flag like this :

constructor(props){
  super(props);
  this.state = {
    hasScrolled: false
  }
}

Then add this method :

onScroll = () => {
 this.setState({hasScrolled: true})
}

Hook it up to FlatList:

<FlatList
onScroll={this.onScroll}

Finally load only when scrolled :

handleLoadMore = () => {
  if(!this.state.hasScrolled){ return null; }

  //here load data from your backend

}