0
votes

I am implementing pagination in react native app my Web API is giving total record size and option to send page no as a parameter. www.URL.com/api/GetAll?pageNo={pageNumber}. Currently I'm using the standard approach i.e:

 let pageNumbers = TotalRecords/PageSize;
       for(i=0; i<pageNumbers; i++)
       {
             pageNumberArray[i] = i + 1;
       }
this.setstate({pageNumber: pageNumberArray})




render()
{
this.state.data.map(function (data, index)
        {
<Card>
<CardItem>
<Text>SHOWING DATA HERE {data.Title}</Text>
</CardItem>
</Card>
}
{/*SHOWING PAGE NUMBERS*/}
    {this.state.totalRecrods > 1 && 
    <View>
 <FlatList
 height={50}
 style={{padding:10}}
    data={ this.state.pageNumber }
    renderItem={({item}) => <Text style={{backgroundColor:'rgb(191, 219,215)', margin:5,height:50}}>{item}</Text>}
   keyExtractor={(item, index) => index}
   horizontal={true}
/>
</View>

    }
}

Now I have standard page numbers and on click on every page number I called the URL again with respective page number and update the data state that shows next 50 records.

The issue is I don’t like this traditional approach in mobile app. I want to implement the Card View such that on scroll it automatically loads another 50 records. Not showing page numbers to the user and saving all time clicking on page number to go to next page.

2

2 Answers

3
votes

You can use below code. Please note that ListService.getList is a function which calls the api end point with relevant page number.

class List extends Component {

    constructor() {
        super();
        this.state = {
            list: [],
            pageNumber: 1,
        };
        this.fetchList = this.fetchList.bind(this);
        this.onEndReached = this.onEndReached.bind(this);
    }

    fetchList() {
        ListService.getList(this.state.pageNumber)
            .then((response) => {
                this.setState({ list: response.data, pageNumber: this.state.pageNumber + 1 });
            })
            .catch((error) => { });
    }

    onEndReached() {
        this.fetchList();
    }

    render() {
        return (
            <FlatList
                keyExtractor={(item, index) => item.ID}
                data={this.state.list}
                onEndReached={this.onEndReached}
                onEndReachedThreshold={0.3} />
        )
    }
};
0
votes

You can use onEndReached prop of FlatList to know when the list ended and then you can get the next page content then push the received data to your existing data. You can set when the endReached event will fire with onEndReachedThreshold prop.