Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
        });
};
like image 579
Mahdi Bashirpour Avatar asked Jul 10 '18 10:07

Mahdi Bashirpour


2 Answers

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

}
like image 169
Nikolay Tomitov Avatar answered Nov 13 '22 05:11

Nikolay Tomitov


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
            });  
    }
like image 3
FatemehEbrahimiNik Avatar answered Nov 13 '22 04:11

FatemehEbrahimiNik