DEV Community

loading...
Cover image for Build React Native WordPress App [Expo way] #9 : Saving bookmar

Build React Native WordPress App [Expo way] #9 : Saving bookmar

kris
React native developer and Technical writer Americano addicted
Originally published at kriss.io ・3 min read

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 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 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: [],
      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 ) {
      return (
        <TouchableOpacity
          onPress={() => this.removeBookMark(post[0].id)}>
          <MaterialCommunityIcons name="bookmark" size={30} />
        </TouchableOpacity>
      );
    } else {
      return (
        <TouchableOpacity
          onPress={() => this.saveBookMark(post[0].id)}>
          <MaterialCommunityIcons name="bookmark-outline" size={30} />
        </TouchableOpacity>
      );
    }
  }}
/>

we have displayed the bookmark icon template based on the bookmark state. The template has the TouchableOpacity component that wraps the MaterialCommunityIcons 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:

Save Bookmark

Next, we need to use the AsyncStorage component from the React Native core package. For that, we can call from React Native directly Expo will continue to support this feature even it’s already deprecated from React Native core

import {
    View,
    ScrollView,
    AsyncStorage,
    Share,
    TouchableOpacity,
} from 'react-native';

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({bookmark: true});
  };

we have taken the parameter as post id. Then, we have set the 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({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({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


Originally published at Kriss.

Discussion (0)