Codementor Events

Build React Native WordPress App [Expo way] #5 : Pull To Refresh and Infinite scroll

Published Feb 17, 2020
Build React Native WordPress App [Expo way] #5 : Pull To Refresh and Infinite scroll

This series intends to show how I build an app to serve content from my WordPress blog by using react-native. Since we successfully build an app on the React Native CLI path., for the next step, we try to develop this app again but using Expo. We will discover the Expo ecosystem that makes our lives comfortable and help us avoid dealing with Native modules to learn how to deal with WordPress APIs. Here, the most prominent features talked about in the book are the dark theme, offline mode, infinite scroll, in-app purchase, and many more. You can discover much more in this series. this inspiration to do this tutorial series came from the React Native Templates from instamobile

here we continued from the previous chapter that we did on the necessary HTTP request in this section we are going to implement a pull to refresh and infinite scroll that makes Home screen more feature two feature is simple because Flatlist provide comfortable

Pull to refresh

for pull to refresh is we hit long-press and scroll down that make the event for make API request again. We need to define a state variable called isFetching, which will handle the hiding and showing of refresh loader. like the code snippet below:

this.state = { 
     posts:[],
     isFetching: false,
  }

Next, we need to create a function called onRefresh() which will trigger when we pull the pull to refresh the trigger.

onRefresh() { 
  this.setState({ 
     isFetching: true 
  }, 
  function() { 
     this.fetchLastestPost()
   }); 
}

Here, we have changed the state of to true and also called the fetchLastestPost function again. This will cause the re-fetch of the posts by making an API call to the server.

Now, we need to add the onRefresh function to the onRefresh event of the FlatList as shown in the code snippet below:

<FlatList 
  data={ this.state.posts }
  onRefresh={() => this.onRefresh()} 
  refreshing={this.state.isFetching}

And, in the fetchLastestPost function, we also need to change the state of isFetching too false to hide the scroll loader.

async fetchLastestPost() { 
  const response = await fetch('https://kriss.io/wp-json/wp/v2/posts?per_page=5'); 
  const posts = await response.json(); 
  this.setState({ posts: posts, isFetching: false}); 
}

and will try pull to refresh

Infinite scroll

for last in this chapter, we implement infinite scroll that like load more feature when user scroll reach the end of last flatlist item we will make API call for next post item like pagination on a web.

first, we add state for handle page

this.state = { 
 posts:[], 
 isFetching: false, 
 page: 1
}

Next, we are going to create a new function called handleLoadMore and call it in the onEndReached event of the FlatList. We are also configuring some additional props to the FlatList such as onEndReachedThreshold which controls the trigger of function based on how far we are from the bottom of the list. The overall implementation is provided in the code snippet below:

onEndReached={this.handleLoadMore}
onEndReachedThreshold={0.1}
ListFooterComponent={this.renderFooter}

Now, the add  handleLoadMore function is provided in the code snippet below:

handleLoadMore = () => {
    this.setState(
      {
        page: this.state.page + 1,
      },
      () => {
        this.fetchLastestPost();
      },
    );
  };

Here, we have made increment to the page state variable after then called the fetchLastestPost() function again.

Next, we need to make some configuration in the fetching of API as well which will be based on the page number as shown in the code snippet below:

async fetchLastestPost() {
    let page = this.state.page;
    const response = await fetch(
      `https://kriss.io/wp-json/wp/v2/posts?per_page=5&page=${page}`,
    );
    const posts = await response.json();
    this.setState({
      posts: page === 1 ? posts : [...this.state.posts, ...posts],
      isFetching: false,
    });
  }

first, we add page counter to URL that makes load next data set for every new request

second for append new post to state

last thing we add an Activity indicator for show load new data

renderFooter = () => {
    if (this.state.isFetching) return null;
    return (
      <View
        style={{
          paddingVertical: 20,
          borderTopWidth: 1,
          borderColor: "#CED0CE"
        }}
      >
        <ActivityIndicator animating size="large" />
      </View>
    );
  };

now we see the result while test by your self

Conclusion

this chapter we learn to implement two main feature of Flatlist pull to refresh and infinite scroll that simple . for next chapter we will implement loading place holder that show before API call success

Also published on Medium.

Discover and read more posts from Krissanawat Kaewsanmuang
get started