DEV Community

Cover image for Build WordPress App with React Native #10: Setup thensave bookmark
0xAirdropfarmer
0xAirdropfarmer

Posted on • Originally published at kriss.io on

Build WordPress App with React Native #10: Setup thensave bookmark

This series intends to show how I build app to serve content from my WordPress blog by using react-native. Since, my blog is talking about react-native, the series and the articles are interconnected. We will learn how to set-up many packages that make our lives comfortable and 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 and many more. You can discover much more in this series.this inspiration to do this tutorial series came from the React Native Mobile Templates

In case of wanting to learn from the beginning, all the previous parts for this tutorial series are available below:

  1. Build WordPress Client App with React Native #1: Overview
  2. Build WordPress Client App with React Native #2: Setting Up Your Environment
  3. Build WordPress Client App with React Native #3: Handle Navigation with React navigation
  4. Build WordPress Client App with React Native #4: Add Font Icon
  5. Build WordPress Client App with React Native #5 : Home Screen with React native paper
  6. Build WordPress Client App with React Native #6 : Using Html renderer and Moment
  7. Build WordPress Client App with React Native #7: Add pull to refresh and Infinite scroll
  8. Build WordPress Client App with React Native #8: Implementing SinglePost Screen
  9. Build WordPress Client App with React Native #9: implement simple share

Here, we are going to learn how to bookmark the articles so that we can easily access them in our Bookmark screen later. The process is simple. We are going to save post id to Asyncstorage from the SinglePost screen and then fetch the articles on the bookmark screen. Here, we are going to add the bookmark icon to the SinglePost screen and configure its functionality.

But first, we need to define the state variable called already_bookmark in the SinglePost.js file in order to handle the showing of bookmark enabled or disabled icon. For that, we need to use the code from the following code snippet:

  constructor(props) {
        super(props);
        this.state = {
          isloading: true,
          post: [],
          already_bookmark: false,
        };
      }

Then, we need to add the Bookmark icon to the screen. For that, we need to use
the code from the following code snippet:

    <List.Item
                 title={`Published on ${moment(
                   post[0].date,
                   'YYYYMMDD',
                 ).fromNow()}`}
                 right={props => {
                   if (this.state.already_bookmark == true) {
                     return (
                       <TouchableOpacity
                         onPress={() => this.removeBookMark(post[0].id)}>
                         <FontAwesome name="bookmark" size={30} />
                       </TouchableOpacity>
                     );
                   } else {
                     return (
                       <TouchableOpacity
                         onPress={() => this.saveBookMark(post[0].id)}>
                         <FontAwesome name="bookmark-o" size={30} />
                       </TouchableOpacity>
                     );
                   }
                 }}
               />

Here, we have displayed the bookmark icon template based on the
already_bookmark state. The template has the TouchableOpacity component that
wraps the FontAwesome component. In the onPress events we have called the
removeBookMark and saveBookMark function. These functions are use to
bookmark the article or remove the bookmark from the article.

Hence, we will get the following result in the emulator screen:

Next, we need to use the AsyncStorage component from the
@react-native-community/async-storage package. For that, we need to use install
the package first. In order to install the package we need to run the command
from the following code snippet:

    yarn add @react-native-community/async-storage

We can get the information as well as the installation instruction from the
package
documentation.

Now, we need to import this package into our Bookmark.js file as shown in the
code snippet below:

    import AsyncStorage from '@react-native-community/async-storage';

Save Bookmark

Here, we are going to implement the saveBookMark function. For that, we need
to define the function first as shown in the code snippet below:

    saveBookMark = async post_id => {
        this.setState({already_bookmark: true});
      };

Here, we have taken the parameter as post id with asynchronous execution of the
function. Then, we have set the already_bookmark state variable to true.

Now, we need to save the post id of the bookmarked post to the AsyncStorage.
For that, we need to use the code from the following code snippet:

    saveBookMark = async post_id => {
             this.setState({already_bookmark: true});
             let bookmark = [];
             bookmark.push(post_id);
             AsyncStorage.setItem('bookmark', JSON.stringify(bookmark));

     };

Here, we have defined a new array called bookmark and pushed the post id value
into it. Then, we have made use of the setItem function of the AsyncStorage
to save the bookmark. We have saved the bookmark array as a JSON value.

Next, we need to prevent the duplicate bookmarks of the same article. For that,
we need to use the code from the following code snippet:

    saveBookMark = async post_id => {
        this.setState({already_bookmark: true});
        await AsyncStorage.getItem('bookmark').then(token => {
          const res = JSON.parse(token);
          if (res !== null) {
            let data = res.find(value => value === post_id);
            if (data == null) {
              res.push(post_id);
              AsyncStorage.setItem('bookmark', JSON.stringify(res));
            }
          } else {
            let bookmark = [];
            bookmark.push(post_id);
             AsyncStorage.setItem('bookmark', JSON.stringify(bookmark));
          }
        });
      };

Here, we get the bookmark data and then parse it to an array called res. Then, if we have the bookmark data, we search the post_id for the current post. If the post does not exist in the bookmark, then we can add the bookmark to it and prevent duplicate bookmarks. The third case is for the users who have not made any bookmarks yet. Hence, we can normally apply and save the bookmarks using the saveBookMark function.

Summary

In this chapter, we learned how to implement the UI and functionality of the bookmark button using the AsyncStorage module. Using it, we implemented the function to save method

The post Build WordPress Client App with React Native #10: Setup and save bookmark appeared first on Kriss.

Top comments (0)