Mahdi Bashirpour
Mahdi Bashirpour

Reputation: 18803

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

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);
        });
};

Upvotes: 10

Views: 30991

Answers (2)

FatemehEbrahimiNik
FatemehEbrahimiNik

Reputation: 613

constructor(props){
  super(props);
  this.state = {
    loading: true
  }
}

   <FlatList  
 onEndReached={this.handleLoadMore}/>

 handleLoadMore = () => {
        if(!this.state.loading){ return null; }
        
        this.setState({
        page: this.state.page + 1,
        loading: false
        }, () => {
        this.loadProducts(); 
        });
    };

 loadProducts(catId,userkey){
          $this.setState({ 
                loading:true
            });  
    }

Upvotes: 3

Nikolay Tomitov
Nikolay Tomitov

Reputation: 947

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

}

Upvotes: 16

Related Questions