State machines are one of the oldest concepts in computer science but also one of the most useful. When combined together with React, they can drastically reduce bugs and complexity in your code.
Build Real-World React Native App #10 : Setup in-App Purchase in iOS
The most awaited and considerably the lengthiest chapter is here. In this chapter, we will learn how to add the in-app purchase service in React Native using React Native IAP package The configurations are mainly for the iOS platform. Here, we are going to set up the subscriptions and configure the App Store Connect to enable the in-app purchase feature. The process is somewhat lengthy but make sure to do it carefully. We are also going to implement a tester to test the in-app purchase service. Lastly, we are also going to configure the UI screen for the Remove ads feature.
Let’s get started!
Installing React Native IAP
First, we are going to install a package named react-native iap. This is a react-native native module library project for in-app purchases for both Android and iOS platforms. For that, we need to run the following command in our project terminal:
yarn add react-native-iap
Setup on iOS
In iOS, we need to run a general command for cacao pod install as shown below:
cd ios/ && pod install ; cd ..
Then, we need to go to Xcode and add in-app purchase capability as shown in the screenshot below:
As we are done in Xcode, we will see the following information:
To use the In-app purchase service, we need to create a Context component named IApController first. Then, we need to import components as shown in the code snippet below:
import React, { createContext, useState, useContext } from 'react'; import * as RNIap from 'react-native-iap'; import { Alert, Platform } from 'react-native' export const IApContext = createContext();
Then, we need to create an array to contain the product name that will match on both Android and Apple developer dashboard as shown in the code snippet below:
const itemSkus = Platform.select({ ios: [ 'kriss.once.removeads', 'kriss.sub.removeads' ], android: [ 'com.kriss.remove_ads_monthly', 'com.kriss.remove_ad_forever' ] });
Next, we need to create two states to handle product data and ads status as shown in the code snippet below:
export const IApController = ({ children }) => { const [products, setProducts] = useState([]) const [showads, setShowads] = useState(true);
Now, we are going to start with fetching product data from the app store and play store. For Playstore, we need to get a subscription with separate function as shown in the code snippet below:
const initIAp = async () => { try { const products = await RNIap.getProducts(itemSkus); if (Platform.OS === 'android') { const subscription = await RNIap.getSubscriptions(itemSkus); products.push(subscription[0]) } console.log(products) setProducts({ products }); console.log(products) } catch (err) { console.warn(err); // standardized err.code and err.message available } }
Product and Subscription
Now, we need to create two more functions to handle user purchases and subscriptions. The idea is to hide the ads when the purchase or subscription is successful. The coding implementation for this is provided in the code snippet below:
makePurchase = async (sku) => { try { await RNIap.requestPurchase(sku, false).then(async (res) => { toggleAds(false) }); } catch (err) { console.warn(err.code, err.message); } } makeSubscription = async (sku) => { try { await RNIap.requestSubscription(sku, false).then(async (res) => { toggleAds(false) }); } catch (err) { console.warn(err.code, err.message); } }
Then, we need to create a toggle function to display or hide ads as shown in the code snippet below:
const [showads, setShowads] = useState(true); const toggleAds = value => { if (value === true) { setShowads(true); } else { setShowads(false); } };
Next, we need to prepare a list of functions that we want to export to use in other components as shown in the code snippet below:
return ( <IApContext.Provider value={{ initIAp, Showads, products, makePurchase, makeSubscription, }}> {children} </IApContext.Provider> ); }
Hence, we have completed the configuration part of the IApController. Our next step is to activate Context in App.js.
First, we start by importing IApController to App.js file as shown in the code snippet below:
import { IApController } from './src/components/IApController'
Then, we wrap the Navigator with another level of Context component as shown in the code snippet below:
<IApController> <AdmobController> <NetworkController> <ThemeController> <Navigators /> </ThemeController> </NetworkController> </AdmobController> </IApController>
Now, we need to fetch the list of products that we need to activate in Navigator.js. First import the IApContext in Navigator as shown in the code snippet below:
import { IApContext } from './IApController'
Then by using useEffect hook, we activate it every time the app loads as shown in the code snippet below:
export default Navigator = () => { const { initIAp } = useContext(IApContext) useEffect(() => { initIAp() }, [])
Now, when re-running the app, we get a blank array because we didn’t create a product list on the app store or play store as shown in the screenshot below:
App Store Connect
To register for App store Connect, we require a developer account which costs about 99$ per year. To access this feature, we need to set up financial data first. The screenshot of the App Store Connect console is shown below:
Then, we need to go to the My Apps option and create a new App as directed in the screenshot below:
Next, we need to go to the Feature tab as shown in the screenshot below:
App-store connect feature tabThen, we need to select in-App Purchase and also choose Non-Consumable. Hence, we will use this to offer to remove ads forever as shown in the console screenshot below:
Add new consumable itemWe can provide any name in the Reference Name field but Product ID requires the same ID value that we defined In-app configuration as shown in the screenshot below:
Then, we need to fill in pricing and other description as shown in the screenshot below:
Now, it is ready to use as displayed in the screenshot below:
Now next step is to paid subscription option as directed in the screenshot below:
First, we need to choose Auto-Renewable Subscription as shown in the screenshot above and then fill in Reference Name and Product ID as before as shown in the screenshot below:
Then, we need to create a subscription group as shown in the screenshot below:
Next, we need to select the subscription duration which is 1 Month for our app as shown in the screenshot below:
Lastly, we need to select the pricing option which 4.99$ per month as shown in the screenshot below:
Thus, the app store will calculate pricing for every country itself as shown in the screenshot below:
Hence, we have successfully configured the one-time payment and subscription-based payment option as shown in the screenshot below:
Now, we need to create a Tester.
Creating Tester
First, we need to apply a test for users for initial performance in development mode. Thus, we need to go to User and Access as shown in the screenshot below:
Then, we need to create a new tester as directed in the screenshot below:
To use this in the iOS platform, we can register as a Sandbox account as shown in the screenshot below:
Now, we need to re-run the app again using the following command:
react-native run-ios --device "Kris101"
Hence, we will get the product data printed in the terminal as shown in the screenshot below:
Next, we need to create a new screen to handle the in-app purchases.
For that, we need to create a new screen named RemoveAds and import it to the Navigator.js file as shown in the code snippet below:
import RemoveAds from '../screens/RemoveAds';
Then, we need to add it to the same group on the setting screen as shown in the code snippet below:
<Stack.Navigator> <Stack.Screen name="Setting" component={SettingScreen} /> <Stack.Screen name="Feedback" component={Feedback} /> <Stack.Screen name="RemoveAds" component={RemoveAds} /> </Stack.Navigator>
Next, we need to go back to the Setting screen and add a new menu option called RemoveAds as shown in the code snippet below:
<TouchableOpacity onPress={() => navigation.navigate('RemoveAds')}> <List.Item title="Remove Ads" left={() => <List.Icon icon="bullhorn" />} /> </TouchableOpacity>
Now, we have a menu option to navigate to the RemoveAds screen as shown in the emulator screenshot below:
Implementing RemoveAds screen
On this screen, we are going to perform in-app purchase configurations. Thus, we require a privacy policy and terms of use on this screen. First, we need to import the required packages, modules, and components as shown in the screenshot below:
import React from 'react' import HTML from 'react-native-render-html'; import { List, Card, Title, Paragraph, Avatar } from 'react-native-paper';
For UI, we construct the screen using the code from the following code snippet:
const RemoveAds = () => { const htmlContent = ` <p style="textAlign: center;">Recurring billing,Cancel any time.</p> <p style="textAlign: center;">if you choose to purchase a subscription, payment will be charged to your iTunes account,and your account will be charged within 24-hour to the end of the current period.Auto-renewal may be turned off at any time by going to your seting in your iTunes store after purchase.For more information please visit our <br><a href="https://kriss.io/term-of-service/">Terms of Use</a> and <a href="https://kriss.io/privacy-policy-for-kriss/">Privacy Policy</a>.</p> `; return ( <ScrollView> <Card style={{ shadowOffset: { width: 5, height: 5 }, width: '90%', borderRadius: 12, alignSelf: 'center', marginBottom: 10, marginTop: 10 }}> <Card.Title title="Remove Ads" subtitle="Remove all ads that annoy your eye" left={props => <Avatar.Icon {...props} icon="bullhorn" />} /> <Card.Title title="Support content production" subtitle="You help fundarise for produce content" left={props => <Avatar.Icon {...props} icon="human-handsup" />} /> <Card.Content> <Title> Monthly Subscription</Title> <Paragraph>pay monthly for remove ads</Paragraph> <Button icon="cart" mode="contained" onPress={() => console.log('Pressed')}> 4.99$ per month </Button> <Title>One time payment</Title> <Paragraph>pay only one time for remove ads</Paragraph> <Button icon="cart" mode="contained" onPress={() => console.log('Pressed')}> 49.99$ one time </Button> </Card.Content> <HTML html={htmlContent} onLinkPress={(event, href) => { Linking.openURL(href).catch((err) => console.error('An error occurred', err)); }} /> </Card > </ScrollView> ) } export default RemoveAds
Hence, we will get the following result in our emulator screen:
Remove ads screen
Conclusion
Well, this chapter has been an interesting one. We got stepwise guidance on how to configure the in-app purchase in the React Native app using the IAP package. We configured the in-app purchase for the app store configuring the App Store Connect. The main objective of this chapter was to integrate in-app purchase in the React Native project for the iOS platform so that we can use it to buy a subscription to remove ads in the next chapter. To trigger the in-app purchase we also need to UI screen to provide the detailed subscription feature which is connected to the App store connect through the IAP package. Hence, we also created a UI screen to trigger In-app purchases. In this case, to remove the ads.
Hence, in the next chapter, we are going to use it to implement the subscription-based in-app purchase to remove ads from the app.
Build Real-World React Native App #9 : Implementing Remove Ads Feature
One of the simplest ways to make money from apps is through Advertisements. Hence, we have a popular ads network for mobile that is Admob. There are many ways to implement ads in our app. We can simply pick some ideas from the play store and implement them.
Build Real-World React Native App #8 : implement Dark mode
In this chapter, we are going to implement a new feature in our app. The feature is called dark mode which is very prevalent in the app nowadays. The dark mode is configured into any app to make it night friendly or low light friendly.
How to use the redux dev tools to speed up development and debugging
Redux dev tools are development tools used to debug Redux-based applications. In this article, we’ll learn more about how this tool aids the development and debugging of applications.
Building a WordPress Website with React (Frontity)
According to W3tech, nearly 35% of the websites over the internet are powered by WordPress. The development of WordPress has always been center around PHP, but as the use of headless CMS grows, you can now seamlessly build fast websites with React and WordPress using a framework like Frontity.
Svelte for React Developers
Guide to learning svelte from a React developer perspective. Learn how React features like components, props, state, two-way binding are implemented in Svelte….
Build Real-World React Native App #7: Send Feedback with Formik, Yup, Firebase Cloud Function and Sendgrid
In this chapter, we will create a simple form in the Feedback.js file using Formik and submit form data to the Firebase Realtime Database. Then, we will subsequently forward the message to the sender’s email using Cloud Function and Sendgrid. The form will be for users to send their feedback on the post articles and the app.
Let’s get started!
Setup Formik and Yup
First, we are going to install the required packages Formik and Yup. Formik package enables us to build forms whereas the Yup package is for form validation. We are also going to install another package that is react-native-keyboard-aware-scroll-view which enables us to scroll the view upwards when the keyboard pops up from the bottom. This will provide a better user experience. Now, in order to install these packages, we need to run the command given in the following code snippet in our project terminal:
yarn add formik yup react-native-keyboard-aware-scroll-view
Now, we need to open the Feedback.js file and import the necessary packages and their components as shown in the code snippet below:
import React from 'react' import { View, StyleSheet } from 'react-native' import { TextInput as Input, Button, HelperText } from 'react-native-paper' import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view' import { Formik } from 'formik'; import * as Yup from 'yup'
Next, we need to create a simple form using Formik. First, we need to set the initial input values as blank. When a user submits the form, we need to call the submitForm function which will also display an error if any using helper text. The function that returns the form configuration is provided in the code snippet below:
const Feedback = () => { return ( <Formik initialValues={{ email: '', name: '', message: '' }} onSubmit={(values, { setSubmitting }) => { console.log(values) submitForm(values); setSubmitting(false); }} validationSchema={FeedbackSchema} > {({ handleChange, handleBlur, handleSubmit, values, isValid, dirty, errors, touched, isSubmitting }) => ( <KeyboardAwareScrollView> <View style={styles.container}> <Input placeholder={'Name'} onChangeText={handleChange('name')} onBlur={handleBlur('name')} value={values.name} underlineColor="transparent" mode="outlined" /> <HelperText type="error" visible={errors.name && touched.name} > {errors.name}</HelperText> <Input placeholder={'Email'} onChangeText={handleChange('email')} onBlur={handleBlur('email')} value={values.email} underlineColor="transparent" mode="outlined" /> <HelperText type="error" visible={errors.email && touched.email} > {errors.email}</HelperText> <Input placeholder={'Message'} onChangeText={handleChange('message')} onBlur={handleBlur('message')} value={values.message} underlineColor="transparent" mode="outlined" multiline={true} numberOfLines={12} /> <HelperText type="error" visible={errors.message && touched.message} > {errors.message}</HelperText> <View > <Button icon="email" disabled={!isValid} mode="contained" onPress={handleSubmit}> Submit </Button> </View> </View> </KeyboardAwareScrollView> )} </Formik> ) } export default Feedback
Next, we need to create the validation rules using Yup as shown in the code snippet below:
const FeedbackSchema = Yup.object().shape({ name: Yup.string() .min(2, "name is Too Short!") .max(50, "name is Too Long!") .required("name is Required"), // recaptcha: Yup.string().required(), email: Yup.string() .email("Invalid email") .required("Email is Required"), message: Yup.string() .min(12, "message is Too Short!") .max(50, "message is Too Long!") .required("message is Required"), });
Hence, we will get the form view as shown in the emulator screenshots below:
And, when we submit the form with empty fields, we will get the error message as well as shown in the emulator screenshots below:
Now that we have the form view, we will move on to set up Firebase in our React Native project.
Setting up React Native Firebase
Here, we are going to use the react-native firebase version 6 package in order to access Firebase services. Initially, we only require the core Firebase package and real-time database. So, we need to install them using the command provided below:
yarn add @react-native-firebase/app @react-native-firebase/database
Setup on iOS
In iOS, we start by installing React native Firebase on cacao pod by using the command provided below:
cd ios ; pod install
Next, we need to open the project with Xcode and find the Bundle identifier as shown in the screenshot below:
Next, we need to go to Firebase Console and create a new app. Then, choose an iOS app and add Bundle identifier as shown in the example screenshots below:
Next, we need to download the GoogleService-info.plist file as shown in the screenshot below:
Then, we need to move the plist file to the Xcode project structure as shown in the screenshot below:
Next, we need to open Appdelegate.m file in Xcode and import Firebase then activate [FIRApp configure]; as highlighted in the example screenshot below:
Now, if everything works according to the right setup then we will see the following status on Firebase when we re-run the app:
Setup on Android
For Android, we need to locate the file named MainApplication.java as shown in the screenshot below:
Then, we need to copy the package name back to the Firebase console. The package name that we will get in the MainApllication.java file is shown below:
package com.kriss;
After copying, we need to create a new android app in the Firebase console and paste the package name in the config form as shown in the screenshot below:
After that, we will get the google-service.json file which we need to download as shown in the screenshot below:
After downloading, we need to copy it to the location as shown in the screenshot below:
Next, we need to open android/build.gradle and add classpath as ‘com.google.gms:google-services:4.2.0’ to dependencies as shown in the code snippet below:
buildscript { ext { buildToolsVersion = "28.0.3" minSdkVersion = 16 compileSdkVersion = 28 targetSdkVersion = 28 } repositories { google() jcenter() } dependencies { classpath("com.android.tools.build:gradle:3.4.2") classpath 'com.google.gms:google-services:4.2.0' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } }
Then, we also need to add apply plugin: ‘com.google.gms.google-services’ configuration to the last line of android/app/build.gradle file as shown in the code snippet below:
task copyDownloadableDepsToLibs(type: Copy) { from configurations.compile into 'libs' } apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project) apply from: "../../node_modules/react-native-vector-icons/fonts.gradle" apply plugin: 'com.google.gms.google-services'
Hence if we re-run the app, we will get the following logs in our metro bundler:
Now, if everything works fine, we will get the following result in our Firebase:
Using Database package
Here, we go back to Feedback.js and import Firebase realtime database package as shown in the code snippet below:
import database from '@react-native-firebase/database'
First, we need to create a function named submitForm and call the realtime database as shown in the code snippet below:
const submitForm = (values) => { database() .ref("feedback/") .push(values) .then(res => { alert("thank for giving feedback"); }) .catch(err => { console.error(err); }); }
Now, if we try to submit the form, we will get an alert as shown in the emulator screenshot below:
In order to make a navigation link to the Feedback screen, we need to add a menu option to our Settings.js screen file. For this, we need to use the code from the following code snippet:
import React, { useContext, useState } from 'react'; import { View, TouchableOpacity } from 'react-native'; import { List, Switch, } from 'react-native-paper'; import React, { useContext, useState } from 'react'; import { View, TouchableOpacity } from 'react-native'; import { List, Switch, } from 'react-native-paper';
Then, we need to use the TouchableOpacity component to implement clickable menu option as shown in the code snippet below:
const Setting = ({ navigation }) => { return ( <View style={{ flex: 1 }}> <TouchableOpacity onPress={() => navigation.navigate('Feedback')}> <List.Item title="Send Feedback" left={() => <List.Icon icon="email" />} /> </TouchableOpacity> </View > ); } export default Setting;
Here, we have added a navigation configuration to the Feedback screen using the navigate function provided by the navigation option.
Hence, we will get the following result as shown in the emulator screens below:
Sending email with Firebase Cloud Function
The last thing we need to do is to forward a message to the user’s inbox using the Firebase cloud function.
For that we need to install the firebase-tools package globally using NPM as shown below:
npm install -g firebase-tools firebase login
Here, we are also logging into Firebase services. As a result, we will get the following success message:
Then, by running the Firebase init command, we need to choose the required Firebase CLI feature function as shown in the screenshot below:
Next, we need to choose the Firebase project as highlighted in the screenshot below:
Now, we need to open the firebase functions folder by running the following command.
code functions/
Hence, we can now start implementing the Firebase project. The project structure is shown in the screenshot below:
Now, in order to send the email, we are going to use Sendgrid. So, we need to install it first by running the following command:
npm i @sendgrid/mail
Next, we need to open the index. file and import firebase functions and Sendgrid main module. We also need to setup Sendgrid with a new API key as shown in the code snippet below:
const functions = require('firebase-functions'); const sgMail = require("@sendgrid/mail"); sgMail.setApiKey("Sendgrid api key");
Next, we need to call an event observer onCreate that will trigger when new data is added to the database as a new column that we define. Then, we need to call Sendgrid and send an email. The overall coding implementation for this is provided in the code snippet below:
exports.sendEmailConfirmation = functions.database .ref('/feedback/{orderId}') .onCreate(async (snapshot, context) => { const val = snapshot.val(); const mailOptions = { from: '[email protected]', to: '[email protected]', subject: 'Hey new message from ' + val.name+':'+val.email, html: '<b>' + val.message + '</b>', }; sgMail .send(mailOptions) .then(res => { return res.json({ result: "Success", message: `Email has been sent to ${email}. ` }); }) .catch(res => { // console.log('SIGNUP EMAIL SENT ERROR', err) return res.json({ result: "error", message: res.message }); }); return null; });
Finally, we send this function to Firebase by using the command provided below:
firebase deploy
And now, when we open the Function menu in the Firebase console, we will see the following configuration:
Hence, if we submit the Feedback form again from our React Native app, we will get an email notification as shown in the emulator screenshot below:
Hence, we have successfully implemented the Feedback screen with the form submit feature and also setup Firebase along with Sendgrid to send an email notification when the form is submitted.
Conclusion
In this chapter, we learned some important features and packages. First, we learned how to implement a form interface using the Formik package and validate it using the Yup package. Then, we got a detailed insight on how to set up Firebase on both Android and iOS platforms. Lastly, we also learned how to set up the Firebase Cloud Function and send email notifications using Sendgrid.
All code available on Github.
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:
- First, we get bookmarked data from Asyncstorage.
- Next, we convert the string data to the array form.
- Then, we loop through the strings and create a query string for fetching the post.
- 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:
While the Bookmark screen with bookmarked posts is shown in the emulator screenshots below:
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:
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:
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.
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:
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:
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:
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:
- First, we set the local state to true.
- Next, we checked if the post exists.
- Since AsyncStorage stores data as plain text, we need to convert objects to a compatible format.
- Then, we checked if the post_id exists by using shorthand JS.
- If not, we use a push method to store data.
- 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:
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.