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.
Node.js Lesson 13: Debugging in Node.js
Since debugging is this important, it’s almost a skill that we must learn to be a better programmer and ship features quickly. In this lesson, we will learn about debugging a node application. We will learn about different ways which can be employed to debug node application with ease.
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….
Real-Time Subscriptions with Vue and GraphQL
In this tutorial, we will move from setting up and deploying graphql backend with Hasura cloud to consuming the subscription endpoint on the vue.js application by building a project.
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.
Node.js Lesson 12: HTTP Module and Nodemon
Hey everyone, today we will dive deeper into the HTTP module and learn it’s functionality. We will learn about what are the function provided that can be helpful and how to use them. We will also learn about nodemon and improve our development process. Let’s start.
Advantages and disadvantages of remote work
Most people think that working remotely is being free most of the day, working just a couple of hours at the beach and uploading selfies to Instagram. This is not true. At least not 100% true.
Spring Security Basics
Spring Security is a framework for securing Spring-based applications. In this article, we will look over the core Spring Security concepts.
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.