You are on page 1of 48

© Copyright 2022 M.

Furqan - All rights


reserved.

The content in this book may not be reproduced,


duplicated, or transmitted without direct written
permission from the author or publisher.

Under no circumstance will any blame or legal


responsibility be held against the publisher, or
author, for any damages, reparation, or monetary
loss due to the information contained within this
book. Either directly or indirectly. You are responsible
for your own choices, actions, and results.

Legal Notice:

This book is copyright protected. This book is only for


personal use. You cannot amend, distribute, sell, use,
quote, or paraphrase any part, or the content within
this book, without the consent of the author or
publisher.

Disclaimer Notice:

Please note the information contained within this


document is for educational and entertainment
purposes only. All effort has been executed to present
accurate, Up to date, and reliable, complete
information. No warranties of any kind are declared
or implied. Readers acknowledge that the author is
not engaging in the rendering of legal, financial,
medical, or professional advice. Please consult a
licensed professional before attempting any
techniques outlined in this book.

By reading this document, the reader agrees that

under no circumstances is the author responsible for

any losses, direct or indirect, which are incurred as a

result of the use of the information contained within

this document, including, but not limited to errors,

omissions, inaccuracies .

OceanofPDF.com
Hashing passwords using bcryptjs in node js| Complete
React Course Article #49
Creating Login Endpoint & sending auth token| Complete
Hashing passwords using bcryptjs in nodejs| Complete React
Course Article #49 React Course Article #50
Creating a middleware to decode user from a JWT |
Complete React Course Article #51
Fetching all notes & Adding a Note | Complete React Course
Article #52
Updating an existing Note | Complete React Course Article
#53
Endpoint for deleting a Note | Complete React Course Article
#54
iNotebook React Project Setup | Complete React Course
Article #55
Creating Navbar and Routes | Complete React Course Article
#56
Introduction to React Context API | Complete React Course
Article #57
useContext hook: Using React Context API | Complete React
Course Article #58

OceanofPDF.com
Hashing Passwords using
bcryptjs in NodeJs |
Complete React Course
Article #49
In the previous article, we learned the concept of Password
Hashing, Salt and Pepper. In this article, we will implement
Password Hashing using bcryptjs in Nodejs. So without
further ado let’s begin:
Installing bcryptjs package
Bcryptjs is a nodejs package that will help us in
implementing password Hashing, salt and pepper in Nodejs
easily. To install bcryptjs you can use the below command -

npm i bcryptjs

Using bcryptjs
Bcrypt works in two regular steps. In the first step, we will
generate the salt and secondly, we will hash the password
with the generated salt.

1. Generating Salt

To generate the salt you can simply use the below


command:

const salt = await bcrypt.genSalt(10);


Explanation: Here, we have used the ‘await’ keyword
before a function to make the function wait for this promise
to be resolved. Here, we have used the default value of the
salt round, which is 10. In our case, we have generated the
salt and will perform the hash in the separate function call.
However, You can salt and hash the password in one
function.
2. Hash a Password
First of all import bcryptjs in authjs by entering the below
command:
const bcrypt = require('bcryptjs');

Earlier for the demo purpose, we have used the password as


plain text, but in the previous article, we have seen its
consequences. Therefore, we are declaring a new variable
name secure password which we will be using in the
password field of the create user function. Here we have
passed two parameters, Password and Salt, to the
bcrypt.hash as shown below:

Figure 1.1: Hash a Password

Result: Now, let’s open the thunder client collection and


post a request to check out the result as shown below. As
you can see, this time the password returned as a response
is a Hash.
Figure 1.2: Result
Adding Login Authentication
Till now, whenever someone was logged in to the database,
we were showing him/her their details as a response. It is
obvious that we will be returning something else to the
client. In our case, we will be returning a token, way of
authentication, to the client as a response. There are many
types of authentication techniques available on the web, but
in this course, we will use JWT authentication.

JWT (JSON web token)

JWT is a JSON web token npm package, which helps in


verifying a user. JWT helps in facilitating secure
communication between the server and the client. JSON web
token consists of three parts- Header, Payload, and
Signature.

Header: The information contained in the header describes


the algorithm and the token type used to generate the
signature.
Payload: It contains the data you want to send, this data is
used to provide authentication to the party receiving the
token.
Signature: Whenever we dispatch a JSON web token from
the server, we will sign the token with secrets. Here’s how
we can create a JWT secret:
const JWT_SECRET = 'Harryisagoodboy';

Using JSON Web Token(JWT)


First of all, we will import the JSON web token by entering
the below command in the Auth.js file:
var jwt = require('jsonwebtoken');

Now, we will send a token having a user-id instead of a User


as a response. After that we will use the sign method as
shown below:

Figure 1.3: Using JSON Web Token

Explanation: Above, we have created a data object


containing a user-id. After that, we have created the
‘authtoken’ function in which we have used the jwt.sign
method. Jwt.sign method takes two parameters and returns
the promise. Remember, the jwt.sign is a sync function thus,
there is no need of using async-await. Finally, we have
returned the ‘authtoken’ as a response by using the res.json
command.

Result: Now let’s check the response by sending a request


as shown below. Here, we are getting the token in response
to the request. Now, whenever someone returns the auth
token then we can easily convert it into data, and with the
help of JWT secret we can easily find out if someone has
tampered with the data or not. Ideally, the client must not
have changed the payload data.

Figure 1.4: Result


So, here we complete the 49th article of this React series. In
the upcoming articles, we will be creating some more useful
endpoints for our react application. In addition to this, we
will be learning more about middlewares and will enhance
our iNotebook application.

Thank you for being with me throughout the tutorial. In the


next tutorial we will be Creating Login Endpoint & sending
auth token. Till then, Keep learning and Keep Coding.

OceanofPDF.com
Creating Login Endpoint &
sending auth token|
Complete React Course
Article #50
In the previous article, we have sent an auth token to one of
our endpoints. In this article, we will add a new endpoint to
authenticate a user in the auth.js file. So, let’s dive straight
into it:
Authenticate a User
Till now, we have created a signup user endpoint in
"auth.js". In a similar fashion, we are going to create a login
endpoint to authenticate the user as shown below:

Figure 1.1: Authenticate a User

Explanation: Above, We have added a validation check for


the Email and the password. If the client enters an invalid
email or left the password field blank then the app will throw
the occurring error with a bad request. This simply means
we won’t bother the server to fetch data from the database
if an error occurs.
Comparing Email
However, In an ideal scenario, we would like to fetch the
client data from the database after comparing the entered
email with the actual email present in the Database.
Therefore, We would use the destructuring method of
javascript to get email and password from the req.body and
would use the try-catch syntax as shown below:

Figure 1.2: Comparing the Entered Email with Actual one

Explanation: In try, we would like to fetch ‘User’ having the


entered email-id and password of the client. If we don’t find
any existing user in the database with the given email, then
we would throw an error with a custom message to the
client.
Comparing Password
After comparing the client email we would compare the
entered password of the client with the user actual
password as shown below:

Figure 1.3: Comparing Password and sending Payload


Explanation: Remember to use the await in
bcrypt.compare as it is an asynchronous function. Similarly,
As we have done for email, if the password doesn’t match
up then we would show an error message to the client.
However, if both the fields(Email and Password) are correct
then we would send the payload to the user. In catch, we
would simply send an error to the user with a custom
message, as we have done earlier.

Result: We would post a request, with correct credentials,


at the /api/auth/login endpoint as shown below:

Figure 1.4: Result

Here, we are getting the auth token while entering the


correct credentials. However, if we have entered the wrong
email id and password then the application will throw an
error.

So, here we complete the 50th article of this React series. In


the upcoming articles, we will be using all these endpoints
in our iNotebook application. In addition to this, we will be
creating some new endpoints for our iNotebook application.

Thank you for being with me throughout the tutorial. In the


next tutorial we will be Creating a middleware to decode
user from a JWT. Till then, Keep learning and Keep Coding.
OceanofPDF.com
Creating a middleware to
decode user from a JWT |
Complete React Course
Article #51
In the previous article, we have created some routes in the
backend of our iNotebook application. In today’s article, we
would create a new route, which will provide us with the
details of the logged-in user. So, without further ado let’s
begin!
Creating 'Get user' Route
We would be creating a new route to get the details of the
logged-in User using Post requests. Remember, that to use
this route, a login is required. This simply means that we
need to send the JWT token to this route. Let’s create the
route in a similar fashion as we have done before:

Figure 1.1: Creating a 'Get User' route

Explanation: Here, we have used the try-catch syntax to


allow us to define a block of code to be tested for errors
while it is being executed. In try, we would wait for the user
ID to be fetched, which will be coming from the token. Here,
just for demo purposes, we have assumed that we get the
user id (todo). After that, we are finding the user by its
received user-id from the token. Subsequently, we would be
showing all the details of the user by using the select
method, except the password.
Decode User ID from JWT
Now, we will be decoding the authtoken to get the user id
and then we will pass the user id to our third route.
Remember, that we have sent the user id in the authtoken,
in the previous article.
Getting Started
We will send a header having auth-token to all the request
which requires the user to be authenticated. After that, we
would extract the data from the header and would fetch it in
the third route. However, if we write the extraction code of
the User ID in our third route, then we have to copy-paste it
to every endpoint which requires user authentication. To
overcome this issue we are going to use middleware.
Middleware in Nodejs
In our case, middleware is a function that will be called
whenever a request will be made in the 'login required'
routes.
Creating Middleware
We are creating a middleware folder, inside which we are
creating a "fetchuser.js" middleware. In "fetchuser.js"
middleware, we would write a function as shown below:
Figure 1.2: Creating Middlewares

Explanation: Let’s understand the above code in three


steps:

1. Step 1: Above, we have first imported the


Jsonwebtoken (JWT). After that, we have created a fetch
user arrow function, which takes request, response, and
next.
2. Step 2: After that, we would like to get the token from
the header named auth-token. Moreover, if the token is
not present then we have denied access to the user
with a bad request.
3. Step 3: Subsequently, we have extracted the data
from the token and have verified the token and the
JWT_secret. Hence, we would get the user and therefore
we would execute the next function. The next() function
is not a part of the Node.js or Express API but is the
third argument that is passed to the middleware
function. This means that the async (req, res) will be
called after getting the user in the ‘getuser’ route.
Enhancing the Third Route
This time, we have the user id appended in the request
therefore we have used req.user.id to get the user-Id.
Finally, we have sent the user details as a response as
shown below:

Figure 1.3: Enhancing the third Route

In Thunderclient:

In the get user endpoint, we would append the authtoken in


the header and will make a post request at the ‘get user’
endpoint as shown below:

Figure 1.4: Testing the response of the Endpoint


Hence, we have successfully fetched all the details and now
these details can easily be taken to the frontend.
So, here we complete the 51st article of this React series. In
the upcoming articles, we will be using all these endpoints
in our iNotebook application. In addition to this, we would be
creating some new endpoints for our iNotebook application.

Thank you for being with me throughout the tutorial. In the


next tutorial we will be Fetching all notes & Adding a Note.
Till then, Keep learning and Keep Coding.

OceanofPDF.com
Fetching all notes &
Adding a Note | Complete
React Course Article #52
In the previous article, we have created a middleware and a
new endpoint to fetch the details of a user with the help of a
JWT token. In today’s video, we will be creating a 'add
Notes' and 'fetchallNotes' endpoint. So, without further ado
let’s begin:
Creating a new Route - Fetch All
Notes
Now, we will be creating a new 'fetchallNotes' route, which
will provide the client with all the notes of him/her, by
fetching them from the database. Remember, it will be
providing the notes to only those clients who are logged in.
We would be using get requests as we have to simply take
the token from the header.

Figure 1.1: Creating Fetch All Notes Route

Explanation: Above, we have used the find() method to get


all the notes of the specific user. Notice that we have used
the async and await function while creating the fetch all
notes route. Here, we have used the get request, as we
have to simply take the token from the header. After getting
the notes, we will be sending them as a response. In this
case, we have used the try-catch syntax as we have done
previously.
Testing the Endpoint - Thunder Client
Now, let’s check the 'FetchallNotes' endpoint in thunder
client by making a get request as shown below:

Figure 1.2: Testing the Endpoint - Thunder Client

Result: You must have noticed that here we are getting the
empty array as a response. This happens as no notes are
available at this instance. However, if notes were available
then all the notes would have been shown as a response.
Associating the Notes with User
We would like to show the notes, stored in the database of
the iNotebook application, of the client to him/her only to
maintain and protect the privacy of the user. To add this
functionality in the application, we have to somehow
associate the Notes with the user. Here’s how we are gonna
do that:
Figure 1.3: Associate the Notes with User

Explanation: Above, in the Notes model, we have first


imported the schema in the Notes model. After that, we
have created a user field in the NotesSchema. Inside the
User field, we have used the schema type to specify what a
given path should have and what values are valid for that
path. If you have ever used SQL then you can compare it
with the foreign key. In the second line of code, we have
added the user model as a reference model. As a result,
now we can store users in the Notes.
Creating a New Route - Add Note
Earlier, we have got an empty array as a response on the
'fetchallNotes' endpoint. This had happened as no notes
were available for display. Therefore, we will create a new
route to add new notes. It will be a post-request route, and it
will help us to add a new note to our application.
Figure 1.4: Creating a New Route - Add Note

Explanation: Here, we are creating an Add Note Route.


Moreover, we are also using the express validator to check
the notes, as we have done previously. Once the notes are
successfully validated without showing any error then we
would like to save the new note.
Saving a New Note
We can easily save the new no te in the database of the
iNotebook application as shown below:

Figure 1.5: Saving the Notes

Explanation: To save the new notes in the database follow


the below-mentioned steps:

1. Step 1: Firstly, we would get the title, description and


tag from the req.body with the help of the destructing
method of javascript.

2. Step 2: After that, we have added the title,


description, tag and the specific user in the New Note
object.

3. Step 3: Finally, we have used the save() function to


save the notes in the database and have returned the
notes as a response to the client. If you remember, we
have already learnt how to save a note in the database.
Checking Results - Saving notes
Now, let’s check the add note endpoint in thunder client by
making a Post request and adding a random note as shown
below:

Figure 1.6: Testing the Endpoint - AddNote

Result: Here, we have passed some random values to the


title, description, and tag field. As a result, we have got the
user detail as a response and all the notes data is being
added in the database corresponding to that specific user.
Remember, the user must be logged in to access this
endpoint.
In thunder client- Fetching Notes
Now, let’s check the fetch all Notes endpoint in thunder
client by making a get request to fetch all the notes of a
specific user as shown below:

Figure 1.7: Testing the Endpoint - Fetch All Notes

Here, as a result, all the notes of the specific user have been
successfully fetched.

So, here we complete the 52nd article of this React series.


In the upcoming articles, we would be creating some new
endpoints, like a delete note, an Update note endpoint, etc,
for our iNotebook application.

Thank you for being with me throughout the tutorial. In the


next tutorial we will be Updating an existing Note. Till then,
Keep learning and Keep Coding.

OceanofPDF.com
Updating an existing Note
| Complete React Course
Article #53
In the earlier videos, we have learnt how to create notes
and save them in the database of the iNotebook application.
In today’s video, we will be learning how to update an
existing note. So, without further ado let’s begin:
Creating Route - Updating Note
We will be creating a new endpoint that will help us to
update an existing note in the database. Remember, that
we will make sure that the user is logged in for accessing
the update Note endpoint. To create a new route follow the
below steps:

Figure 1.1: Creating the updating Note Route

Explanation: We have to provide the id of the note, which


we would like to update. Firstly, we have used the
destructuring method of Javascript to get the title,
description, and tag from the body. After that, we have
created a new note object, in which we have added the
functionality to set the updated title, description, and tag
field in place of the existing fields of the note. Here, we
have used the put request to create a new resource or
update an existing one.
Error - Note doesn't exist
Firstly, we will allow the server to find the notes which are
requested by the client as shown below:

Figure 1.2: Note Not Exist

Explanation: Here, we have used the findById() method to


get the notes by their ID. However, if the server fails to find
the notes that means the notes did not exist in the
database. In that condition, we will be showing a not found
error to the user.
Validating the User
Now, we will be adding a validation check so that a logged-
in user can only update his/her notes and don’t tamper with
the notes of another user.

Figure 1.3: Validating the User

Explanation: Here, we are validating if the note belongs to


the logged-in client or not. To do so we have extracted the
user-id and have evaluated it with comparison to the
logged-in user-id, to check if it is the same user who has
created the note or not. However, if the match of user-id
fails then we will unauthorize the logged-in user from
accessing the notes of others.
Find and Update Note
However, If both the above-mentioned conditions are
satisfied, that is the note exists in the database and the
user id correctly matches with the logged-in user id. In that
circumstances, we will find and update the note by using
the findByIdAndUpdate() method as shown below:

Figure 1.4: Find and Update Note


Testing the Update Note Endpoint
Now, let’s check the update Note endpoint in thunderclient
by making a put request to update a note as shown below:

Figure 1.5: Testing and Update Note endpoint


Result: Here, as you can clearly see, our notes have been
successfully updated. You can also make a get request to
fetch all notes endpoint to make sure if the notes are
updated in the database or not.

So, here we complete the 53rd article of this React series. In


the upcoming articles, we will be creating a delete note
endpoint and understand some more concepts of React.

Thank you for being with me throughout the tutorial. In the


next tutorial we will be making Endpoint for deleting a Note.
Till then, Keep learning and Keep Coding.

OceanofPDF.com
Endpoint for deleting a
Note | Complete React
Course Article #54
In the previous article, we have created an Update Note
endpoint. In this article, we will create an endpoint for
deleting a Note. So, without further ado let’s begin:
Creating Route - Delete Note
We will create the delete Note endpoint in a similar way, as
we have created the update Note endpoint. Remember,
here we will be using the ‘delete’ request method in place of
‘put’ request as shown below:

Figure 1.1: Using Delete Request


Find the Note
Firstly, we will allow the server to find the notes which are
requested by the client as shown below:

Figure 1.2: Find the Note for Deletion

Explanation: Here, we have used the findById() method to


get the notes to delete by their ID. However, if the server
fails to find the notes that means the notes did not exist in
the database. In that case, we will be showing a not found
error to the user.
Validating the User
Now, we will allow the user to delete the note only if the
user owns the note otherwise not. Here’s how we can do
that:

Figure 1.3: Validating the User

Explanation: Here, we are validating if the note belongs to


the logged-in client or not. To do so we have extracted the
user id and have evaluated it with comparison to the
logged-in user-id, to check if it is the same user who has
created the note or not. However, if the match of user-id
fails, then we won’t authorize the logged-in user to access
the notes of others.
Find and Delete Note
However, If both the above-mentioned conditions are
satisfied, that is the note exists in the database and the
user-id correctly matches with the logged-in user id. In that
circumstances, we will find the note by its id and delete the
note by using the findByIdAndDelete() method as shown
below:
Figure 1.4: Find And Delete the Note
Testing the Delete Note Endpoint
Now, let’s check the delete Note endpoint in thunderclient
by making a delete request to delete a note as shown
below:

Figure 1.5: Testing the Delete Note Endpoint

Result: Here, as you can clearly see, our notes have been
successfully deleted. Now, if the client tries to delete the
same note twice they will face an error, as the note has
been already deleted.
So, here we complete the 54th article of this React series. In
the upcoming articles, we will begin working on the client-
side and would be understanding some more new concepts
of React.

Thank you for being with me throughout the tutorial. In the


next tutorial we will be setting up iNotebook React Project.
Till then, Keep learning and Keep Coding.

OceanofPDF.com
iNotebook React Project
Setup | Complete React
Course Article #55
In the previous article, we finally finished setting up the
backend of the iNotebook application. From now on, let
begin setting up the frontend and connect it with the
created backend of the iNotebook application. So, without
further ado let’s begin:
Getting Started with Frontend
Firstly, we will completely set up the front end of the
iNotebook app. After that, in the upcoming articles, we will
connect the backend with the frontend to complete our
iNotebook application. Let’s install some npm package in
the package.json of react application.

1. React router: It provides a way to introduce different


pages or routes in our React application without reloading
the page. To install react-router, use the below command:

npm i react-router-dom

2. Concurrently: Concurrently is an npm package that


allows us to use more than one server concurrently. To
install concurrently, use the below command:

npm i react-router-dom concurrently

In package.json - React App


We want to start our backend and the react app
simultaneously with the help of concurrently. Therefore, we
will add the below piece of code in the script of
package.json

"both": "concurrently \"npm run start\" \"nodemon


backend/index.js\""

Result: Now, you can run both servers, by executing the


‘both’ in the terminal as follow:
npm run both

iNotebook application: Now, we will simply remove all the


unwanted files and code from the application and will add
some text in app.js, as we want to display something in our
iNotebook application. Here’s the first look at the iNotebook
application:

Figure 1.1: iNotebook application

So, here we complete the 55th article of this React series. In


the upcoming articles, we will be enhancing the iNotebook
application by adding components, bootstrap, and much
more.

Thank you for being with me throughout the tutorial. In the


next tutorial we will be Creating Navbar and Routes. Till
then, Keep learning and Keep Coding.

OceanofPDF.com
Creating Navbar and
Routes | Complete React
Course Article #56
In the previous article, we have begun setting up the front
end of our React App. Let’s continue the journey by creating
Navbar and Routes for our iNotebook application. So,
without further ado let’s begin:
Adding Bootstrap to our React App
(iNotebook)
In the Documentation of Bootstrap, we will find the starter
template which has two main things to add bootstrap in our
application.
1. Bootstrap bundle with popper: It contains the
Jquery files, Bootstrap.js, and popper.js files. Copy the
code and paste it inside the body tag of index.html of
the react application.
2. Bootstrap CSS: It contains the CSS files to enhance
your application. Simply, Copy the code of Bootstrap
CSS and add it inside the head tag of Index.html (In the
Public folder) of the iNotebook application.
Now, we can easily use the components of Bootstrap in our
Application. Remember the following points while copying
the code from bootstrap in the react application:
● Close those tags which don't have a closing tag.
● Replace the ‘class’ keyword with ‘ClassName’.
● Replace href= “#” with href= “/”
● The code must be in one tag or use a JSX fragment.
Note: In this tutorial, we will be moving quickly while
setting up some basic things in the iNotebook application,
as we have already learned the basics while creating the
TextUtils and NewsMonkey application.
Creating components
We are creating a components folder, in which we will
create the following components :

1. Home: we will add some random text, like ‘This is


Home’ in Home.js to identify the component while
opening the iNotebook application.
2. About: we will add some random text, like ‘This is
About’ in About.js to identify the component while
opening the iNotebook application.
3. Navbar: in Navbar.js, we will copy-paste and edit the
code of a Navbar, from Bootstrap to save some time.

After creating the components, we will simply import and


use the components in App.js. But before that let’s quickly
look up the setup of react-router.
Setting up Router
Install React Router package
First of all, we have to install the react-router package,
because it is not a part of the core react library. To do this,
open the terminal and execute the below piece of code:
npm install react-router-dom

Set Up routing for our application


The first thing you have to do is go to the root component,
that is, your app.js file, and import Browser Router as
Router, Switch, Route, and Link from react-router-dom. To
import the following using the below command:
Import {BrowserRouter as Router, Switch, Route, Link} from
"react-router-dom"

1. Using Router: Now, we have to surround our entire


application with the router component. Hence, To
surround your app with the router component, use
<router></router>.

2. Using Switch: The switch component makes sure that


only one route shows at any one time. All of our routes
go inside this switch component.

3. Using Route: Alright, we need to set up our individual


routes for the About and Home components. At this
moment, we have two pages of our application, and
hence we are going to place two routes inside this
switch component. Remember to replace the anchor
tag with the ‘link’ tag for the proper working of the
react-router. Have a look at the setup of react-router for
our iNotebook application :
Figure 1.1 Setting Up React Router

Here, We have nested our component inside the route which


will be displayed when the user visits that specific route.
More importantly, this all will occur without the reloading of
the page.

So here we complete the 56th article of this React series. In


the upcoming articles, we will be creating some more new
components, State, etc and will be understanding some
amazing concepts of React.

Thank you for being with me throughout the tutorial. In the


next tutorial we will get an introduction to React Context
API. Till then, Keep learning and Keep Coding.

OceanofPDF.com
Introduction to React
Context API | Complete
React Course Article #57
In the previous article, we have begun working with the
front end of the iNotebook application. In today’s video, we
would be learning about context API, which helps a react
developer in managing complex applications. So, without
further ado let’s begin!
Why use Context API?
At a very high level, A react app consists of ‘state’ and
‘components’. As we already know that every component in
React has its own state. Due to this reason, building and
managing a complex application that has a large number of
states and components isn’t an easy task. We can resolve
this issue with the help of state lifting technique as
mentioned below:
Understanding State Lifting
In a layman language, this simply means sharing a state
from one common source. State lifting is accompanied by
lifting the state to the parent component as a source to pass
the state to the children components.
Figure 1.1: Performing State Lifting

Explanation: In the case of the above app, we can create


all the states in app.js(Parent component) as a javascript
object, and now we can pass the state to child components.
But, there still exists one major problem with this kind of
approach. Let's understand this!
Understanding Prop Drilling Issue
Prop drilling is a situation when the same data is being sent
at almost every level due to requirements in the final level.
Let’s assume that in the above application we have to check
if the user is logged in while accessing the ‘clothing’ and
‘o2’ menus. In this scenario, if we use the state lifting
method then we have to pass the logged-in state from
app.js to every component. Hence, it requires a lot of prop
drilling as shown below:
Figure 1.2: Understanding Prop Drilling Issue

Explanation: Here, we have to send the ‘login’ state to the


‘offers’ component and then to the ‘O2’ component. In this
case, we have to perform a ton of prop drilling to use the
logged-in state in the ‘offers’ and ‘O2’ Components. Hence,
to resolve such issues in a complex react app, the
developers use an amazing feature available in React,
named Context API.
Understanding Context API
The Context API can be used to share data with multiple
components, without having to pass data through props
manually. Let’s deal with the similar prop drilling issue with
the help of context API as shown below:
Figure 1.3: Understanding Context API

Explanation: In the above case, we have created a color


state in App.js and now we want to use it in C7 and C8. To
do so formally, we have to first pass the color to C7, in order
to reach C8. A similar situation goes with C7 as well.
However, A react developer can create a context, with the
help of creating a context feature of the API. After doing
that, any of the components in the react application can use
a state directly without prop drilling.

So, here we complete the 57th article of this React series. In


the upcoming articles, we would be using the concept of
Context API in our beloved iNotebook application and would
be understanding some more concepts of React

Thank you for being with me throughout the tutorial. In the


next tutorial we'll be learning about useContext hook. Till
then, Keep learning and Keep Coding.

OceanofPDF.com
useContext hook: Using
React Context API |
Complete React Course
Article #58
In the previous article, we understood the need and working
of the Context API. In this article, we will be using Context
API with the help of useContext hook. So, without further
ado let’s begin!
The Context API - Recall
The Context API can be used to share data with multiple
components, without having to pass data through props
manually. Any state inside a context will become accessible
to every component of the React Application. Now, let’s
begin working with Context API.
Getting Started - Context API
We will create a context folder in Src folder, to store all the
context of the iNotebook application. After that, we will
create a Notes sub folder, which will contain all the context
related to Notes. Finally, we will be creating some files
named NoteState.js and noteContext.js. Remember, with
the help of these two files we will be using and
understanding context API in this article.
Creating Context - In noteContext.js
First of all, we have to import createContext in the file by
using the import command. After that, we will be creating a
new context with the help of a predefined syntax and finally,
we will export the note context as shown in the below
figure:
Figure 1.1: Creating Context - In noteContext.js

Result: Hence, we have successfully created a context for


the iNotebook application. Remember that this context will
be holding all the states related to the notes.
Creating State - In NoteState.js
Now, we will be creating a state which will be accessible to
all the components, which are related to notes. To create
such a state, follow the steps mentioned below:

Figure 1.2: Creating State - In NoteState.js


Explanation: In NoteState.js, first of all, we will import
noteContext in NoteState.js as shown above. Subsequently,
we have created a state object having ‘name’ and ‘class’
items inside the ‘NoteState’ arrow function and finally have
returned the NotesContext.Provider, having the values
which we want to provide to our components. The Provider
component accepts a value prop to be passed to consuming
components that are descendants of this Provider. Here, the
NoteContext provider contains all the children components,
which means that we have to just wrap the
application(app.js) inside <NoteState></NoteState>, in
order to use the above-created state in every Component
and Subcomponents.
Using the Created Context -In
About.js
Let’s check if the created context is working or not. In our
case, we are using the ‘about’ component for testing
purposes.

Figure 1.3: Using the Context


Explanation: Above, we have first imported the note
context. After doing that, we have used the ‘useContext’
method to accept the values provided by note context.
Hence, we have successfully used the ‘name’ property from
the state object (Created in NoteState.js).

Result: Hence, in the 'about' endpoint we will be getting


the string that we have passed as a state.
Updating the State
In NoteState.js, we will be creating an update function,
which will help us in updating the ‘s1’ state. In the update
function, we have made an update in the ‘Name’ and ‘class’
fields of the state after 1 second. Remember, to import
‘useState’ from React and to pass the ‘update’ in the value
of the context Provider.
Figure 1.4: Updating the State
Using the Update Function -In
about.js
Now, we will be using the use effect hook in about.js to
update the context. Here’s how we are gonna do that:
Figure 1.5: Using the Update Function
Result: Now, the values of the State will be getting
changed after one second of the reloading of the page. This
simply means that we can also pass the function as context.

So, here we complete the 58th article of this React series. In


the upcoming articles, we will be understanding the use
location hook and will be learning some more amazing
concepts of React.

Thank you for being with me throughout the tutorial. In the


next tutorial we will be learning about useLocation Hook. Till
then, Keep learning and Keep Coding.
Previous

OceanofPDF.com

You might also like