07Dec

Build Real-World React Native App #6: Show Bookmark and Categories

Build Real-World React Native App #6: Show Bookmark and Categories
Build Real-World React Native App #6: Show Bookmark and Categories

Here, we are going to implement the list view of bookmarked posts in the Bookmark screen and also work on implementing the Categories screen. For the post list in the Bookmark screen, we are going to use the post id that we saved to AsyncStorage from the SinglePost screen in the previous tutorial to fetch the articles on the bookmark screen. After that, we are going to implement the Categories screen. This screen will contain the list of categories related to the article posts. And on clicking on these categories, we will navigate to the posts which are based on that respective category. The implementation is simple. We are going to fetch the categories data and display it with the FlatList component. And by using the TouchableOpacity component, we will navigate to the new list screen which will display the list of article posts based on that category.

Let’s get started!

Bookmark List Screen

Now, we need to create a screen to display the posts which have been bookmarked. So, we need to go to the Bookmark.js file as import the required components and packages as shown in the code snippet below:

import React, { useEffect, useState, useContext } from 'react';
import { FlatList, View, Image } from 'react-native';
import FlatlistItem from '../components/FlatlistItem';
import { Headline, Text } from 'react-native-paper';
import ContentPlaceholder from '../components/ContentPlaceholder';
import AsyncStorage from '@react-native-community/async-storage';

Then, we need to define the initial states called bookmarkpost and isloading state to handle the post and preloader as shown in the code snippet below:

   const Bookmark = ({ navigation }) => {
   const [bookmarkpost, setbookmarkpost] = useState([]);
   const [isloading, setisloading] = useState(true);

Next, we need to create a function for fetching the bookmarked post. The coding implementation for this is provided in the code snippet below:

const fetchBookMark = async () => {
       await AsyncStorage.getItem('bookmark').then(async (token) => {
           res = JSON.parse(token);
           setisloading(true);
           if (res) {
               console.log('arr', res)
               const result = res.map(post_id => {
                   return 'include[]=' + post_id;
               });
               let query_string = result.join('&');
               const response = await fetch(
                   `https://kriss.io/wp-json/wp/v2/posts?${query_string}`,
               );
               const post = await response.json();
               setbookmarkpost(post);
               console.log(post)
               setisloading(false);
           } else {
               setbookmarkpost([]);
               setisloading(false);
           }
       });
   };

The coding implementation in the above code snippet is explained below:

  1. First, we get bookmarked data from Asyncstorage.
  2. Next, we convert the string data to the array form.
  3. Then, we loop through the strings and create a query string for fetching the post.
  4. Then, we concatenate the query string to the main URL.

Now, we have successfully completed the implementation of the Bookmark List screen.

Using Focus Hook
In order to update data every time a user navigates to the Bookmark screen, we are going to use the Focus hook from react-navigation to detect screen focus events. First, we need to import the hook function as shown in the code snippet below:

import { useIsFocused } from '@react-navigation/native';

Then, we need to create a new constant as shown in the code snippet below:

const isFocused = useIsFocused();

And, also use useEffect hook to observe isFocused event as shown in the code snippet below:

useEffect(() => {
       fetchBookMark();
   }, [isFocused]);

Lastly, we need to make the conditional rendering to display the screen with data or without the data as shown in the code snippet below:

if (isloading) {
       return (
           <View style={{ marginTop: 30, padding: 12 }}>
               <ContentPlaceholder />
           </View>
       );
   } else if (bookmarkpost.length == 0) {
       return (
          <View style={{ textAlign: 'center', alignItems: 'center', alignSelf: 'center' }}>
               <Image source={require('../assets/image/nobookmark.png')} />
           </View>
       );
   } else {
       return (
           <View>
               <Headline style={{ marginLeft: 30 }}>Bookmark Post</Headline>
               <FlatList
                   data={bookmarkpost}
                   renderItem={({ index, item }) => (
                       <React.Fragment>
                           <FlatlistItem item={item} navigation={navigation} />
                       </React.Fragment>
                   )}
                   keyExtractor={(item, index) => index.toString()}
               />
           </View>
       );
   }

Hence, the Bookmark screen without any bookmarked posts is shown in the emulator screenshots below:

Bookmark is not found. Result
Bookmark is not found. Result

While the Bookmark screen with bookmarked posts is shown in the emulator screenshots below:

Show bookmark post
Show bookmark post

Hence, we have successfully implemented the bookmark feature along with Bookmark List screen.

Implementing Categories Screen

First, we need to import the necessary component in the Category.js screen as shown in the code snippet below:

import React, { useState, useEffect, useContext } from 'react';
import { FlatList, ScrollView, View, TouchableOpacity } from 'react-native';
import ContentPlaceholder from '../components/ContentPlaceholder';
import { Card, Title } from 'react-native-paper'

Next, we need to create a functional component that receives a navigation option as a parameter. We also need to define some state variables to handle the preloaders and categories data as shown in the code snippet below:

   const Categories = ({ navigation }) => {
   const [isloading, setisloading] = useState(true);
   const [categories, setCategories] = useState([]);

Now, we need to create a function that fetches data from WordPress Api. First, we need to set the loading state to true to show the content placeholders until the data has been fetched. After the data is fetched successfully, we will display the fetched data and hide the loading placeholders. For that, we need to use the code from the following code snippet:

const fetchCategorie = async () => {
       setisloading(true);
       const response = await fetch(`https://kriss.io/wp-json/wp/v2/categories`);
       const categories = await response.json();
       setCategories(categories);
       setisloading(false);
   };

For the initial load, we need to call the function inside the useEffect hook as shown in the code snippet below:

useEffect(() => {
       fetchCategorie();
   }, []);

Next, we start implementing the UI part. The UI implementation is the same in which we will set the conditional rendering to show either preloaders or a categories data in FlatList as shown in the code snippet below:

if (isloading) {
       return (
           <View style={{ marginTop: 30, padding: 12 }}>
               <ContentPlaceholder />
           </View>
       );
   } else {
       return (
            <FlatList
                   data={categories}
                   renderItem={({ item }) => (
                       <TouchableOpacity
                           onPress={() =>
                               navigation.navigate('CategorieList', {
                                   categorie_id: item.id,
                                   categorie_name: item.name,
                               })
                           }>
                           <Card>
                               <Card.Content>
                                   <Title>{item.name}</Title>
                               </Card.Content>
                           </Card>
                       </TouchableOpacity>
                   )}
                   keyExtractor={(item, index) => index.toString()}
               />
         );
   }
}
export default Categories

Hence, we will get the following result on our emulator screen:

Categories screen
Categories screen

 

Display Categories list

Now, we need to create a screen that will show the list of posts based on a particular category. This screen will be the same as the Home screen. Only the post will be based on the category we choose. Here, we are going to add pull to refresh and infinite scroll as well.

First, we need to create a new component screen name CategorieList.js in the components folders. Then, we need to make the following imports to the file:

import React, { useEffect, useState, useContext } from 'react';
import { FlatList, View, ActivityIndicator } from 'react-native';
import ContentPlaceholder from '../components/ContentPlaceholder';
import FlatlistItem from '../components/FlatlistItem';

Next, we need to define the state variables for posts, page, fetching and loading states as shown in the code snippet below:

const CategorieList = ({ navigation, route }) => {
   const [posts, setPosts] = useState([]);
   const [isloading, setIsLoading] = useState(true);
   const [isFetching, setIsFetching] = useState(false);
   const [page, setPage] = useState(1);

The posts state is for handling the fetched post, isloading state to handle the display of preloaders, and the page state to handle the fetched page from the server.

Now, we need to make use of useEffect hook to observe events for pull to refresh and infinite scroll as shown in the code snippet below:

useEffect(() => {
       fetchLastestPost();
   }, []);
   useEffect(() => {
       if (isFetching) {
           fetchLastestPost();
       }
   }, [isFetching]);
   useEffect(() => {
       if (page > 1) {
           fetchLastestPost();
       }
   }, [page]);

Now, in order to fetch the data from WordPress API, we are going to implement an asynchronous function and use the category id and page queries in the URL as shown in the code snippet below:

const fetchLastestPost = async () => {
       let categorie_id = route.params.categorie_id;
       const response = await fetch(
           `https://kriss.io/wp-json/wp/v2/posts?categories=${categorie_id}&per_page=5&page=${page}`,
       );
       const post = await response.json();
       if (page == 1) {
           setPosts(post);
       } else {
           setPosts([...posts, ...post]);
       }
       setIsLoading(false);
       setIsFetching(false);
   };

Then, we need to create two functions to handle pull to refresh and infinite scroll as shown in the code snippet below:

function onRefresh() {
       setIsFetching(true);
   }
   function handleLoadMore() {
       setPage(page => page + 1);
   }
   function renderFooter() {
       if (isFetching) return null;
       return (
           <View
               style={{
                   paddingVertical: 20,
                   borderTopWidth: 1,
                   borderColor: '#CED0CE',
               }}>
               <ActivityIndicator animating size="large" />
           </View>
       );
   }

We need the preloader content placeholder to the render method as well. We are going to use isloading state to handle the showing and hiding of preloaders as shown in the code snippet below:

if (isloading) {
       return (
           <View style={{ marginTop: 30, padding: 12 }}>
               <ContentPlaceholder />
           </View>
       );
   } else {
       return (
           <View>
               <FlatList
                   data={posts}
                   onRefresh={() => onRefresh()}
                   refreshing={isFetching}
                   onEndReached={() => handleLoadMore()}
                   onEndReachedThreshold={0.1}
                   ListFooterComponent={() => renderFooter()}
                   renderItem={({ index, item }) => (
                         <FlatlistItem item={item} navigation={navigation} />
                      )}
                   keyExtractor={(item, index) => index.toString()}
               />
           </View>
       );
   }
};
 
export default CategorieList;

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

Categories list screen
Categories list screen

Finally, we have completed the implementation of Categories Screen in our project.

Conclusion

In this chapter, we made use of the AsyncStorage and fetch method to successfully fetch the bookmarked post to be displayed on the Bookmark screen. Then, we went on to implement the overall UI of the Categories screen as well as the Categories List screen. We learned how to fetch the categories of different posts from the WordPress API. Then, we implemented the navigation to the Category List screen where we learned how to fetch the articles post based on the category id and display them as a list. Then, by clicking on the article posts we navigated to the SinglePost screen.

In the next chapter, we will learn how to use Formik, Yup, and Firebase to create a simple form.

All code available on Github.

 

02Dec

Build Real-World React Native App #5: Single Post Screen and Bookmark

Build Real-World React Native App #5: Single Post Screen and Bookmark
Build Real-World React Native App #5: Single Post Screen and Bookmark

We have already implemented the Home screen in which the posts are shown in list format. Now, what happens when we tap on a post from the screen? Until now, nothing will happen. But, now we are going to create a screen that will display the details of the post. This screen will be called the SinglePost screen which we will implement in the SinglePost.js file.

The SinglePost screen will contain the detail of the entire post optimized for reading purposes. We are also going to add a share button which will be functional as well. The share button allows users to share the post on social media and other platforms. For displaying the data format properly, we are going to take the help of the moment.js package. The moment.js is a powerful Date and Time library that allows us to configure the date and time format in various ways. The package has its implementation for every framework of JavaScript.

The idea is to begin by implementing a SinglePost Screen and setting up the navigation to it through the list of posts in Home Screen or any other screen. We are going to add the share button and bookmark button as well. Lastly, we are going to make use of the async-storage to store the bookmarked posts and display them in the Bookmark Screen.

Let’s get started!

Create Single Post Screen

First, we need to create a Singlepost.js in screens folders. Then, we need to make the necessary imports as shown in the code snippet below:

import React, { useState, useEffect, useContext } from 'react';
import {
   Avatar,
   withTheme,
   Card,
   Title,
   Paragraph,
   List, Button
} from 'react-native-paper';
import HTML from 'react-native-render-html';
import ImageLoad from 'react-native-image-placeholder';
import {
   Share,
   ScrollView,
   TouchableOpacity,
   View,
   Dimensions,
} from 'react-native';
import ContentPlaceholder from '../components/ContentPlaceholder';
import moment from 'moment';

Next, we need to create a functional component called SinglePost and define a state variable to handle the loading of the post data as shown in the code snippet below:

const SinglePost = ({route}) => {
   const [isLoading, setisLoading] = useState(true);
   const [post, setpost] = useState([]);     
}
export default SinglePost

Here, the parameter route enables us to fetch the data sent as a parameter from other components.

Now, we are going to create a function in order to fetch the post details data based on the post id that we receive from the route params. The post detail data will be stored in the post state that we defined before as shown in the code snippet below:

const fetchPost = async () => {
       let post_id = route.params.post_id;
       const response = await fetch(
           `https://kriss.io/wp-json/wp/v2/posts?_embed&include=${post_id}`,
       );
       const post = await response.json();
       setpost(post);
       setisLoading(false);
      
   }

Then, we need to use useEffect to trigger the function every time the component loads as shown in the code snippet below:

useEffect(() => {
       fetchPost()
   }, []);

And, when we successfully fetch the data and store it on our post state, we will use the components from the react-native-paper package to create the UI and display the post data appropriately. The overall coding implementation is provided in the code snippet below:

return(
     <ScrollView>
               <Card>
                   <Card.Content>
                       <Title>{post[0].title.rendered}</Title>
 
                       <List.Item
                           title={`${post[0]._embedded.author[0].name}`}
                           description={`${post[0]._embedded.author[0].description}`}
                           left={props => {
                               return (
                                   <Avatar.Image
                                       size={55}
                                       source={{
                                           uri: `${post[0]._embedded.author[0].avatar_urls[96]}`,
                                       }}
                                   />
                               );
                           }}
                       />
                       <List.Item
                           title={`Published on ${moment(
                               post[0].date,
                               'YYYYMMDD',
                           ).fromNow()}`}
                       />
                       <Paragraph />
                   </Card.Content>
                   <ImageLoad
                       style={{ width: '100%', height: 250 }}
                       loadingStyle={{ size: 'large', color: 'grey' }}
                       source={{ uri: post[0].jetpack_featured_media_url }}
                   />
                   <Card.Content>
                       <HTML
                           html={post[0].content.rendered}
                           imagesMaxWidth={Dimensions.get('window').width}
 
                       />
                   </Card.Content>
               </Card>
           </ScrollView>
)

Here, the UI code is a mix of different components from the react-native-paper package.

Now, we are going to use content placeholders to display the loading state as well. For that, we are going to use isLoading state to handle the display of preloaders as shown in the code snippet below:

if (isLoading) {
       return (
           <View style={{ paddingLeft: 10, paddingRight: 10, marginTop: 10 }}>
 
               <ContentPlaceholder />
           </View>
       )
   } else {
       return (
           <ScrollView>
           </ScrollView>
       );
   }

Hence, we will get the result as shown in the emulator screenshot below:

Single post screen
Single post screen

Adding a Share button

This is an extra section for this chapter where we are going to add a share button in SinglePost.js screen which enables us to share the post.

First, we need to import Share component from the React Native package and also import the required fonts from the react-native-vector-icons package as shown in the code snippet below:

import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';

Next, we need to create a function to handle share action called onShare as shown in the code snippet below:

const onShare = async (title, uri) => {
       Share.share({
           title: title,
           url: uri,
       });
   };

Here, we are using the share function provided by the Share component. The parameters applied are the title and the post URI.

Finally, we need to add the TouchableOpacity component in order to make the share button clickable as shown in the code snippet below:

<List.Item
       title={`Published on ${moment(
            post[0].date,
            'YYYYMMDD',
        ).fromNow()}`}
              right={props => {
                 return (
                    <TouchableOpacity
                        onPress={() =>
                          onShare(post[0].title.rendered, post[0].link)
                    }>
                    <MaterialCommunityIcons name="share" size={30} />
                         </TouchableOpacity>
                       );
                    }} />

Hence, we will get the following result in our emulator screens:

Add share button
Add share button

As we can see, there is a share button on the right side of the screen. Now, if we tap on the share icon, the share option modal will open as shown in the emulator screenshots below:

Share button result
Share button result

Finally, we have successfully implemented the SinglePost screen along with preloaders and a Share button.

Bookmark with AsyncStorage

Here, we are going to learn how to implement the bookmark feature using async-storage to bookmark the posts so that we can easily access them on our Bookmark screen. The process is simple. We are going to save the post id to AsyncStorage from the SinglePost screen.

Installing AsyncStorage

Here, we are going to continue to setup async-storage package for storing the bookmarked posts and then fetching it in the Bookmark screen.

First, we need to install the package provided by the React Native community using the following command in our project terminal:

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

Setup on iOS
In iOS, we need to install cacao pod and re-run the app again using the following commands:

cd ios ; 
pod install ; 
cd .. ; 
react-native run-ios --device "Kris101"

Setup on android

There is no need to do anything if the React native version is greater than 0.60. Talking about which our React Native version is greater than 0.60. But in the case of lower versions, we will need to run the react-native link command.

Now, we need to go to the SinglePost.js file and import the Asyncstorage component as shown in the code snippet below:

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

Before storing the data ton AsyncStorage, we need to use local state data to handle the data as shown in the code snippet below:

const [bookmark, setbookmark] = useState(false);

Here, we are using bookmark as a state variable and setbookmark function in order to change the state of the state variable.

Saving the Bookmarked Post

In order to save the post, we need to create a function that receives post_id. Then, we need to start validating the data as shown in the code snippet below:

const saveBookMark = async post_id => {
       setbookmark(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));
                   alert('Your bookmark post');
               }
           } else {
               let bookmark = [];
               bookmark.push(post_id);
               AsyncStorage.setItem('bookmark', JSON.stringify(bookmark));
               alert('Your bookmark post');
           }
       });
   };

The coding implementation in the above code snippet is explained below:

  1. First, we set the local state to true.
  2. Next, we checked if the post exists.
  3. Since AsyncStorage stores data as plain text, we need to convert objects to a compatible format.
  4. Then, we checked if the post_id exists by using shorthand JS.
  5. If not, we use a push method to store data.
  6. If the initial state is null or empty, we will start by creating a blank array and save data accordingly.

Hence, our save operation is complete.

Removing the Bookmarked Post

In order to remove data from bookmark state array, we use the coding implementation similar to Save operation but replace find function with filter function as shown in the code snippet below:

const removeBookMark = async post_id => {
       setbookmark(false);
       const bookmark = await AsyncStorage.getItem('bookmark').then(token => {
           const res = JSON.parse(token);
           return res.filter(e => e !== post_id);
       });
       await AsyncStorage.setItem('bookmark', JSON.stringify(bookmark));
       alert('Your unbookmark post');
   };

Render the Bookmarked Status Icon

Here, we are going to set the bookmark status state when the screen loads. It will help us know if the post has already been bookmarked or not. For this, we need to use the code from the following code snippet:

const renderBookMark = async post_id => {
       await AsyncStorage.getItem('bookmark').then(token => {
           const res = JSON.parse(token);
           if (res != null) {
               let data = res.find(value => value === post_id);
               return data == null ? setbookmark(false) : setbookmark(true);
           }
       });
   };

Then, we use state to decide which button that we are going to show in the bookmark button icon display. It will either be a bookmarked icon or unbookmarked icon. For this, we need to use the code from the following code snippet:

right={props => {
        if (bookmark == true) {
             return (
              <TouchableOpacity
                    onPress={() => removeBookMark(post[0].id)}>
                       <MaterialCommunityIcons name="bookmark" size={30} />
                          </TouchableOpacity>
                       );
             } else {
              return (
                <TouchableOpacity onPress={() => saveBookMark(post[0].id)}>
                        <MaterialCommunityIcons
                            name="bookmark-outline"
                             size={30}
                         />
                       </TouchableOpacity>
                      );
                 }
       }}

To activate this post, we need to add the renderBookMark function to fetchPost function that is called every time the screen loads as shown in the code snippet below:

const fetchPost = async () => {
        //…./////other code/////…...
       setpost(post);
       setisLoading(false);
       renderBookMark(post_id);
   }

Hence, we will get the following result in our SinglePost screen:

Create a bookmark
Create a bookmark

Here, we can see that the bookmarked post icon status is dark and the post not bookmarked has a bookmarked icon outline only.

Conclusion

In this chapter, we learned how to fetch data from the server using the parameter from the Home Screen. Then, we got an insight into how to use different UI components from the react-native-paper package to display the server response data. We also got stepwise guidance on how to implement a functional share button using the Share component from the react-native package. Lastly, we implemented the Bookmark feature by making use of the async-storage package to store the bookmarked posts and also render out the bookmark icon based on it.

All code in this chapter is available on GitHub.

26Nov

Node.js Lesson 11: Echo Server

Today we are going to learn about Echo Servers. We will go through what are they and how to build them. We will also use this little project to learn about the status code and header of an HTTP request. Let’s start.

20Nov

Automated Postgresql Backups with NodeJS and Bash

The database is the holy grail of your application, but, given the unpredictable nature of software, you should always be prepared for the possibility of media, hardware and software failures. If any of these failures occurs, the main objective should be to ensure the database is back up and running as fast as possible while minimizing user disruption and simultaneously ensuring there is no data loss.

16Nov

Getting started with Next.js

Next.js is a React framework that allows you to build both client and server-side apps. It ships with handy features such as routing, static exporting, server rendering, internationalization.