React Native FlatList Pagination to Load More Data dynamically – Infinite List

React Native FlatList Pagination

Here is an example of React Native FlatList Pagination to Load More Data dynamically – Infinite List. In this example, we will make a FlatList in which we will load the data in the form of pagination on a Click of a button. You can also visit Example of Infinite Loading Listview in React Native using FlatList for the infinite loading list view without load more button.

For those who don’t know what is pagination?

Let’s take a case where you can simply imagine what if Facebook loads all the Facebook posts from the Facebook database on your Facebook wall? Doesn’t it sound nasty? It will take hundreds of hours even more than that so what is the best way to load the data?  Simply paging. When you open Facebook they just show you 10-20 post and while you scroll the Facebook they load the next 10-20 posts in the background. That is what the paging is.

In our example,

  1. We are loading the first 10 posts from the web API call in componentDidMount.
  2. We have added load more button on the footer of the list.
  3. While clicking on the Load More Button we call the Web API again to get the next 10 posts.

We are using a variable offset to manage the index on upcoming Data. We will increase the offset by 1 after the successful call of the web API so that when we call the web API next time we will get the next dataset. So let’s get started with the example.

To Make a React Native App

Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react-native init to make our React Native App. Assuming that you have node installed, you can use npm to install the react-native-cli command line utility. Open the terminal and go to the workspace and run

npm install -g react-native-cli

Run the following commands to create a new React Native project

react-native init ProjectName

If you want to start a new project with a specific React Native version, you can use the --version argument:

react-native init ProjectName --version X.XX.X
react-native init ProjectName --version react-native@next

This will make a project structure with an index file named App.js in your project directory.

Code for Pagination

Open App.js in any code editor and the Replace the code with the following code

App.js

//This is an example of React Native 
//FlatList Pagination to Load More Data dynamically - Infinite List
import React, { Component } from 'react';
//import react in our code.

import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  FlatList,
  Platform,
  ActivityIndicator,
} from 'react-native';
//import all the components we are going to use.

export default class App extends Component {
  constructor() {
    super();
    this.state = {
      loading: true,
      //Loading state used while loading the data for the first time
      serverData: [],
      //Data Source for the FlatList
      fetching_from_server: false,
      //Loading state used while loading more data
    };
    this.offset = 1;
    //Index of the offset to load from web API
  }

  componentDidMount() {
    fetch('https://aboutreact.herokuapp.com/getpost.php?offset=' + this.offset)
    //Sending the currect offset with get request
      .then(response => response.json())
      .then(responseJson => {
      //Successful response from the API Call 
        this.offset = this.offset + 1;
        //After the response increasing the offset for the next API call.
        this.setState({
          serverData: [...this.state.serverData, ...responseJson.results],
          //adding the new data with old one available in Data Source of the List
          loading: false,
          //updating the loading state to false
        });
      })
      .catch(error => {
        console.error(error);
      });
  }

  loadMoreData = () => {
  //On click of Load More button We will call the web API again
    this.setState({ fetching_from_server: true }, () => {
      fetch('https://aboutreact.herokuapp.com/getpost.php?offset=' + this.offset)
      //Sending the currect offset with get request
          .then(response => response.json())
          .then(responseJson => {
          //Successful response from the API Call 
            this.offset = this.offset + 1;
            //After the response increasing the offset for the next API call.
            this.setState({
              serverData: [...this.state.serverData, ...responseJson.results],
              //adding the new data with old one available in Data Source of the List
              fetching_from_server: false,
              //updating the loading state to false
            });
          })
          .catch(error => {
            console.error(error);
          });
    });
  };

  renderFooter() {
    return (
    //Footer View with Load More button
      <View style={styles.footer}>
        <TouchableOpacity
          activeOpacity={0.9}
          onPress={this.loadMoreData}
          //On Click of button calling loadMoreData function to load more data
          style={styles.loadMoreBtn}>
          <Text style={styles.btnText}>Load More</Text>
          {this.state.fetching_from_server ? (
            <ActivityIndicator color="white" style={{ marginLeft: 8 }} />
          ) : null}
        </TouchableOpacity>
      </View>
    );
  }

  render() {
    return (
      <View style={styles.container}>
        {this.state.loading ? (
          <ActivityIndicator size="large" />
        ) : (
          <FlatList
            style={{ width: '100%' }}
            keyExtractor={(item, index) => index.toString()}
            data={this.state.serverData}
            renderItem={({ item, index }) => (
              <View style={styles.item}>
                <Text style={styles.text}>
                  {item.id}
                  {'.'} 
                  {item.title.toUpperCase()}
                </Text>
              </View>
            )}
            ItemSeparatorComponent={() => <View style={styles.separator} />}
            ListFooterComponent={this.renderFooter.bind(this)}
            //Adding Load More button as footer component
          />
        )}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingTop: 30,
  },
  item: {
    padding: 10,
  },
  separator: {
    height: 0.5,
    backgroundColor: 'rgba(0,0,0,0.4)',
  },
  text: {
    fontSize: 15,
    color: 'black',
  },
  footer: {
    padding: 10,
    justifyContent: 'center',
    alignItems: 'center',
    flexDirection: 'row',
  },
  loadMoreBtn: {
    padding: 10,
    backgroundColor: '#800000',
    borderRadius: 4,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  btnText: {
    color: 'white',
    fontSize: 15,
    textAlign: 'center',
  },
});

To Run the React Native App

Open the terminal again and jump into your project using.
cd ProjectName
To run the project on an Android Virtual Device or on real debugging device
react-native run-android
or on the iOS Simulator by running
react-native run-ios (macOS only).

Output Screenshots

After Clicking on Load More It will load the data with the loader in Button

Output in Online Emulator

That was the React Native FlatList with Pagination to Load More Data dynamically. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!

Hope you liked it. 🙂


Related Posts

8 thoughts on “React Native FlatList Pagination to Load More Data dynamically – Infinite List”

  1. first this: this.offset = 0;
    second this: this.offset + 10;
    three this: this.offset + 10;

    10 is quantity itens per page.

    Very good, clean..

    Reply
  2. But this will increase the memory that your application is using on every fetch. The state will becoming larger and larger. Finally, the application will run out of memory. Am I wrong?

    Reply
  3. If we have fetched all the data after specific offset then how to remove the load more icon then? As all the data has been fetched then the load more button would not be necessary there.

    Reply
    • There can be many logics for that but what I usually do is while calling web service I have an idea how much data can come in a single call, for example, service will return 50 data sets in a single call so I make a logic to count the response and if it is 50 then I make the button state visible and if I get less no of data sets then I hide the button as this is the last set of the data. If you want to make the per call number dynamic you can ask your backend developer to send the max number of data set which can come in a single call.

      Reply
  4. Hello, great post.

    I have a question. How to do this without the button, just when you come to the end of the list, it will load the next offset?

    Thanks for the reply,

    Simon.

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.