0% found this document useful (0 votes)
269 views

Master ReactJS Part 3 MFurqan Riaz

Uploaded by

cauliflowers33
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
269 views

Master ReactJS Part 3 MFurqan Riaz

Uploaded by

cauliflowers33
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

© 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
Refactoring News component to use the same function |
Complete React Course Article #33
React Component Lifecycle & Lifecycle methods | Complete
React Course Article #34
Adding Infinite Scroll to NewsMonkey | Complete React
Course Article #35
Adding a top loading bar to NewsMonkey | Complete React
Course Article #36
Hiding API Key by Adding Custom Environment Variables |
Complete React Course Article #37
Introduction to React Hooks | Complete React Course Article
#38
Changing Class based NewsMonkey components to
Functional based | Complete React Course Article #39
Sticky Navbar & NewsMonkey bug fixes | Complete React
Course Article #40
Introduction to MERN stack | Complete React Course Article
#41
Project 3: iNotebook backend and React frontend setup |
Complete React Course Article #42
iNotebook db & Express Server Setup | Complete React
Course Article #43
Creating Routes & Schema for Storing Notes & Users |
Complete React Course Article #44
Storing Data into the Database Using Mongoose Model |
Complete React Course Article #45
Adding Data Validation Using express-validator | Complete
React Course Article #46
Creating ThunderClient Collections to Manage Requests |
Complete React Course Article #47
Understanding Password Hashing, Salt & Pepper | Complete
React Course Article #48

OceanofPDF.com
Refactoring News
component to use the
same function | Complete
React Course Article #33
In the previous article, we have enhanced the NewsItems of
the application. In this tutorial, we would be refactoring our
code as it is unorganized and complex to understand with
too many functions.
Creating update Function
At this time, we are using the same function(updateNews) in
componentDidMount, handlePrevClick, and handleNextClick
function, just with a slight update in the page number. This
time, we would create a function that would be used in
place of writing this same code again and again. So, let’s
create a ‘updateNews’ Function as shown below:

async updateNews(pageNo){
const url = `https://newsapi.org/v2/top-headlines?
country=${this.props.country}&category=${this.props.cate
gory}&apikey=dbe57b028aeb41e285a226a94865f7a7&pag
e=${this.state.page}&pageSize=${this.props.pageSize}`;
this.setState({ loading: true });
let data = await fetch(url);
let parsedData = await data.json()
this.setState({
articles: parsedData.articles,
totalResults: parsedData.totalResults,
loading: false
})
}

Here, we are passing the page number in the function as it


is different at different places of the function. Now, we
would be using this function in place of calling different
functions each time. This allows us to make any changes to
our application very swiftly.
Using the Update News Function
Below, we have used the "updateNews" Function while
invoking the componentDidMount, handlePrevClick, and
handleNextClick function.
For componentDidMount
Inside componentDidMount, we would like to render the
newsItems by using the Update News Function as shown
below:

async componentDidMount(){
this.updateNews();
}

For HandlePrevClick
In the handlePrevClick function, we would like to run the
update news function by decreasing the state of page
number by 1 as shown below:

handlePrevClick = async () => {


this.setState({ page: this.state.page - 1 });
this.updateNews();
}

For HandleNextClick Function


Similarly, In the handlePrevClick function, we would like to
run the update news function by increasing the state of
page number by 1 as shown below:

handleNextClick = async () => {


this.setState({ page: this.state.page + 1 });
this.updateNews();
}

NewsMonkey Application: Hence, after removing the


unnecessary logic from our NewsMonkey application the app
is looking more concise and neat. There is no big change in
the application but the same task is being performed by a
more precise and optimized code.

Figure 1.1: The NewsMonkey Application

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


the upcoming articles, we will be enhancing our application
and would discuss the lifecycle method of React.

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


next tutorial, we will be learning about React Component
Lifecycle & Lifecycle methods. Till then, Keep learning and
Keep Coding.

OceanofPDF.com
React Component
Lifecycle & Lifecycle
methods | Complete React
Course Article #34
Earlier, we refactored the code of the NewsMonkey
application. In today’s article, we will discuss the
Component lifecycle Methods in React. But before that, we
would refactor the little bit code of the NewsMonkey app. So
without further ado let’s begin.
Changing the Title Dynamically
At this point in time, the title in the NewsMonkey application
is fixed. But we would like it to change, whenever the user is
navigating between different News categories. To do so we
would make the following changes in the Constructor:

Figure 1.1: Changing the title of the application

Here, we have used the category props, which is passed


from app.js, and also a function to capitalize the first letter
of the Title. Now, on selecting a specific category the title
also changes accordingly.
Changing the Heading of Application
dynamically
In a similar manner, we would be changing the heading of
the NewsMonkey application as shown below:
<h1 className="text-center" style={{ margin: '35px 0px'
}}>NewsMonkey - top
{this.capitalizeFirstletter(this.props.category)}
Headlines</h1>

Result: Thus, when the user navigates between the


different categories then the ‘heading’ as well as the ‘title’
of the Application changes accordingly as shown below:

Figure 1.2: Title and heading are changing Dynamically


Hence, we have successfully changed the title and heading
of the application dynamically.
React Component Lifecycle Method
Component LifeCycle: The series of events that happens
from the mounting of a React Component to its unmounting.
Mounting: Birth of your component
Update: Growth of your component
Unmount: Death of your component
Here, we would discuss only the most important component
lifecycle method. So, let’s begin understanding component
lifecycle methods.
Methods in React Component
Lifecycle
● render() Method: It is used to render the HTML of the
component in React. It is used to render the DOM while
using the class-based component. Remember, Inside
the Render method we cannot modify the state in
React.
● componentDidMount(): This method executes after
the component output has been rendered to the DOM.
We have already used this method in the NewsMonkey
Application for fetching the Data from the API. You can
also use setState, async, and await methods in
ComponentDidMount().
● componentDidUpdate(): This method is used to
update the DOM in response to the prop or state
changes. Remember that props are read-only. That’s
why here, ‘changes in the prop’ means that it can be
received again in the component.
● componentWillUnmount(): It is invoked just before
the component is unmounted and destroyed. It is
usually used to perform cleanups.
These are the four most commonly used React Component
Lifecycle methods.
React Lifecycle methods diagram by
wojtekmaj.pl
Here’s how the diagram looks like:
Figure 1.3: React Lifecycle Methods Diagram

Here’s the sequence of the methods that will run while


Mounting, Unmounting, Updating the React component.
While Mounting
In this case, the ‘Constructor’ runs first after that the
‘render’ lifecycle method is invoked. After that, React will
update the DOM and finally, the ComponentDidMount will be
executed.
While Updating
The three possible ways in which one can update the React
component are:
1. New props
2. Using setState
3. Using forceupdate()
After updating the component, the render method will be
executed at the start. After that react updates the "DOM and
references" and in the end, the componentDidUpdate
method will be run.
While Unmounting
At the time of unmounting, only the componentWillUnmount
method will be executed and the component will be
unmounted.

Here, we complete the 34th article of this React series. In


the next articles, we will be enhancing the NewsMonkey
Application by adding some more features and
understanding some amazing concepts of React.

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


next tutorial, we will be adding infinite scroll to
NewsMonkey. Till then, Keep learning and Keep Coding.

OceanofPDF.com
Adding Infinite Scroll to
NewsMonkey | Complete
React Course Article #35
In an earlier article, we have learned about the component
life cycle method of React. In this article, we would add an
infinite scroll to the News Monkey application. So, without
further ado let’s begin:
Removing Previous and Next Button
Firstly, we will remove the Next/Previous button and the
function assigned to them, as instead of those buttons we
would be using the Infinite scroll to render all the available
NewsItems on one page.
Installing react-infinite-scroll-
component
To start using the Infinite scroll, we have to install the react-
infinite-scroll-package npm package by using the below
command:

npm i react-infinite-scroll-component
In News.js:

Previously, we were returning a given set of NewsItems


when the loading was false. As for now, we would
concatenate more data in the already rendering data. That
means, while scrolling down, more data will be added in the
NewsComponent. To do so follow the below steps:
1. Adding Infinite Scroll
Firstly, make sure to import Infinite scroll and then add the
infinite scroll in News Component as shown below:

Figure 1.1: Using Infinite Scroll

Explanation: Above, we have set the data length equal to


the article length. We would be creating a "fetchMoreData"
function later on. After that, to check if more articles are
available for rendering in the NewsComponent we have
used "hasMore". Inside the constructor, remember to set the
total results equal to 0. Finally, we have added the spinner
component in the Loader.
2. Creating fetchMoreData Function
We have to write a function to render more NewsItem.
Here’s the code of the fetchMoreData function:

fetchMoreData = async () => {


this.setState({ page: this.state.page + 1 })
const url = `https://newsapi.org/v2/top-headlines?
country=${this.props.country}&category=${this.props.cate
gory}&apikey=dbe57b028aeb41e285a226a94865f7a7&pag
e=${this.state.page}&pageSize=${this.props.pageSize}`;
let data = await fetch(url);
let parsedData = await data.json()
this.setState({
articles: this.state.articles.concat(parsedData.articles),
totalResults: parsedData.totalResults,
loading: false,
})
};

Explanation: In the fetchMoreData function, we have set


the state of the page number and have fetched the
previously used Data. After that, We have concatenated the
"parsedData.articles" in articles.
Result: Hence, we have successfully added an Infinite Scroll
bar to the application.

Figure 1.2: NewsMonkey Application

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


the upcoming articles, we will be enhancing our application
by adding a top-loading bar and learning some amazing
concepts of React.

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


next tutorial, we will be adding a top-loading bar to
NewsMonkey. Till then, Keep learning and Keep Coding.
OceanofPDF.com
Adding a top loading bar
to NewsMonkey |
Complete React Course
Article #36
In this article, we would be adding a top-loading bar to the
NewsMonkey application. It is a great way of displaying the
progress in the application, as the page didn’t load in apps
built using react.
Installing React loading bar package
First of all, we have to install a react loading bar npm
package by using the below command:
npm i react-top-loading-bar

It is a very easy-to-use package. This package can be used


in two ways:
1. With the help of 'ref'
2. With the help of 'state'
Here, we would be using the second method to add a
loading bar to our application.
Using React Loading bar
Firstly, Make sure to import the Loading bar in "App.js". After
that, add the loading bar in "App.js" as shown below:
Figure 1.1: Using React Loading Bar

Explanation: Above, we have added our desired color,


which is red, to the loading bar. We would create a state
object having progress. Remember, the initial progress in
the state is 0. We are using the state progress in the
progress variable of the loader. After that, we have created
a 'set progress' method to change the 'progress' of the
created state. In the end, we passed the ‘set progress
method to the NewsComponent. This will allow us to set
progress from the NewsComponent. We have also set the
height of the progress bar as 3 to have a clear visible look of
the loader in the application.

In News.js:
As a result of the above steps, we have a function in the
NewsComponent that will allow us to change the state of
the loading bar. So, now we would be using the loading bar
at certain instances with different values. For example:
when the data will be fetched for the very first time, we
would be using set progress as a prop and would set its
value as 10. After the data is being fetched we would set the
progress as 30. In a similar manner, we have set the
progress at different moments. This will provide a smooth-
moving effect to the loading bar.

Figure 1.2: Using Set Progress in NewsComponent


Fixing issue - Source Badge Not
responsive
We have noticed that the 'source News Badge' isn’t
displayed properly in the Mobile Devices as shown below:

Figure 1.3 Source Badge - Not Responsive

To fix this issue we would be adding the Source badge inside


a div container and setting the display, justifyContent,
position, and right CSS properties as flex, flex-end, absolute,
and 0 respectively.

Figure 1.4: Fixing Source badge issue

Result: Here’s the look of our application on android and PC


devices.

Figure 1.5: The NewsMonkey Application

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


the upcoming articles, we will be enhancing the
NewsMonkey Application and would be learning about React
Hooks and their usage.
Thank you for being with me throughout the tutorial. In the
next tutorial, we will be Hiding API Key by Adding Custom
Environment Variables. Till then, Keep learning and Keep
Coding.

OceanofPDF.com
Hiding API Key by Adding
Custom Environment
Variables | Complete React
Course Article #37
Earlier, we customized the Newsmonkey application by
adding some features. In this article, we will be learning how
to hide the API key by adding the Custom Environment
variable. So, without further ado let’s begin-
API Exhausted issue
Well, thank you everyone for exhausting the API key of the
NewsMonkey application. As a result, we are facing an error
in our application. Thus, we would be hiding the API key with
the help of the environment variable.
Hiding the API key
Firstly, we will define the environment variable in the ".env"
file. Remember that, by default, the ".env.local" file is
included in the ".gitignore". After that, we would be fetching
the API key from the ".env" file in an API key variable. In the
end, we would be passing the apiKey variable as a prop in
the news update and FetchMoreData function of
NewsComponent.
1. Defining Environment variable
Firstly, create a ".env.local" file, and let’s define an
environment variable inside it. Remember, whenever you
start any environment variable, It must be prefixed with
REACT_APP_ then only you get access to that variable in
your React Application. Here’s how we are going to define
the permanent environment variable in the ".env" file.
REACT_APP_NEWS_API= "dslkhpdsoiher32sdgsoihg3oisdf"

Note: We would be adding our original API key in place of


the fake code and obviously we would not like to make it
public.
2. Fetching the API key
Now, we have to fetch this API key as an object in "app.js".
To do so we would simply add the below code in our
"app.js". Remember that, You can access your environment
variable by using "process.env.prefix".
apiKey = process.env.REACT_APP_NEWS_API

3. Passing the API key as Prop in


NewsComponent
Now, to use the API key we have to first pass the "apiKey"
variable in the NewsComponent as shown below:

Figure 1.1: Passing the API key in NewsComponent


4. Using the API key
Earlier, we used the API key in the 'updateNews' and
'FetchMoreData' function. But this time, we would be using
the API key as a prop as shown below:
const url = `https://newsapi.org/v2/top-headlines?country=
${this.props.country}&category=${this.props.category}&a
piKey=${this.props.apiKey}&page=${this.state.page}&pag
eSize=${this.props.pageSize}`;
Result: Hence, we have successfully hidden the API key of
the News Monkey application. Here’s the look at our
application:

Figure 1.2: NewsMonkey Application

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


the upcoming articles, we will be enhancing the
NewsMonkey Application and would be learning about React
Hooks and their usage.

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


next tutorial, we will get Introduction to React Hooks. Till
then, Keep learning and Keep Coding.

OceanofPDF.com
Introduction to React
Hooks | Complete React
Course Article #38
In this article, we will be having a short introduction to React
Hooks. In addition to that, we will be understanding some of
the most widely used Hooks in React Application. This is so
because in the upcoming videos we will be changing the
class-based component into function-based components, as
they are quite easy when compared with class-based
components.
What are React Hooks?
● React Hooks allows us to use the features of class-
based components in function-based Components.

● It even allows us to use "state" and other React


features without writing a class. For example: Earlier,
we were using "this.state" whenever we needed to
access the state but now we can use the "UseState"
hook.

● Hooks are the functions which "hook into" react state


and lifecycle features from the function components.
Commonly used React Hooks
There are several react hooks to look upon. You can even
create a custom, React Hook. But in this tutorial, we are
covering some of the most commonly used React Hooks:

1. UseState: It is used to update the state and to set the


initial value of the state. The ‘useState’ is similar to
‘this.setState’ in class. The useState returns a pair
where the first element is the current state value/initial
value, and the second one is a function that allows us
to update it. For example: If we create a text variable
and we want to make it a part of the state, then we can
return two elements (like ‘text’ and ‘set text’) from the
state hook.

2. Use Effect: It is used to perform the side effect. For


example: If we want to perform a certain task when the
content of our application is updated, then we can take
the help of the UseEffect hook. In other words, effect
Hooks are similar to componentDidMount(),
componentDidUpdate() and componentWillUnmount()
lifecycle methods.

3. Use Context: This hook allows us to use the context


API. Context API allows us to share data within its
component tree without passing through props. In
short, it helps in removing prop drilling from the
application. Prop drilling is a situation when the same
data is being sent at every level due to requirements.
We will be discussing the Context hook in detail later in
this React Course.

4. UseRef: It returns a mutable reference object, which


has a ".current" property. It can be used to point an
element inside a DOM. In most simple words, it is a
holder which can store an element of the DOM inside its
".current" property.

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


the upcoming articles, we will be refactoring the application
and would be changing class components in function-based
Components.
Thank you for being with me throughout the tutorial. In the
next tutorial, we will be Changing Class based NewsMonkey
components to Functional based. Till then, Keep learning
and Keep Coding.

OceanofPDF.com
Changing Class based
NewsMonkey components
to Functional based |
Complete React Course
Article #39
In the previous article, we have a short introduction to
hooks. In this article, we will be changing the class-based
Components to functional-based components in the
NewsMonkey application. Remember, You can even have a
part of your application as a functional component and the
other part as a class-based component.
Getting Started
We have a total of five components which are Navbar,
Spinner, "App.js", "News.js", "NewsItem.js". So let’s begin
changing these class-based components to the functional
component:

Changing Navbar.js:

Firstly, we will begin refactoring the Navbar component of


the NewsMonkey Application. We can easily change the
class component of "Navbar.js" to a functional component,
by removing the render function and returning the
component in an arrow function as shown below:
Figure 1.1: Changing the Class Component of Navbar.js

Changing Spinner.js:

Similarly, we can make the spinner.js a function-based


component. To do so we have to firstly remove the render
function and after that return the spinner in an arrow
function as shown below:

Figure 1.2: Changing the Class component of Spinner.js

Changing NewsItem.js:

Now, we are going to change NewsItem to a function-based


component as it won't have any side effects in the
NewsMonkey application. To do so, We have to first remove
the render function and after that return, the component in
an arrow function and remember to change ‘this.props’ with
the props keyword.

Figure 1.3: Changing the Class component of NewsItem.js

Hence, we have successfully performed a basic refactor of


the three components of the application.

The next two components, "News.js" and "App.js", are quite


challenging to change to a function-based component, so
without further ado let’s dive straight into it:

Changing News.js

We will first begin changing the ‘proptypes’ and ‘default


Props’ to the function-based component. If you remember,
we can use the prop types in the functional component as
shown below:

News.defaultProps = {
country: 'in',
pageSize: 8,
category: 'general',
}
News.propTypes = {
country: PropTypes.string,
pageSize: Proptypes.number,
category: PropTypes.string,
}

Moreover, we will change the Export class component in an


arrow function. After that, we will be using the ‘usestate’
hook in News.js to update the state and to set an initial
value of the state. To do so firstly, Import the ‘useState’
hook in News.js. As a result, we can now utilize the ‘use
state’ hook inside the function as shown below:

const News = (props) => {


const [articles, setarticles] = useState([])
const [loading, setloading] = useState(true)
const [page, setPage] = useState(1)
const [totalresults, setTotalResults] = useState(0)

Explanation: Since we have set the state with the help of


the 'useState' hook, therefore we can remove the
constructor from the News.js as it is not required anymore.
Now, we can define a state by using the above state
functions, and hence we will remove 'this' keyword, before
declaring any state or variable. Make sure to define
updateNews, fetch more and other functions by converting
them into an arrow function.
Figure 1.4: Changing the News.js

Changing componentDidMount

To perform the task of componentDidMount, we will be


using the useEffect function as shown below:

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

Result: Hence, we have successfully refactored the


application from a class-based component to a function-
based component. Here’s a look at the NewsMonkey
application.
Figure 1.5: NewsMonkey Application

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


the upcoming articles, we will be refactoring the app.js file
and creating a sticky Navbar for the NewsMonkey
Application.

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


next tutorial, we will make Sticky Navbar & fix NewsMonkey
bugs. Till then, Keep learning and Keep Coding.

OceanofPDF.com
Sticky Navbar &
NewsMonkey bug fixes |
Complete React Course
Article #40
In the previous article, we saw how we can refactor the
NewsMonkey application by changing the class components
in a functional-based Component. In this article, we will be
making the navbar sticky and would also be fixing some
bugs in the application. So, without further ado let’s begin:
Sticky Navbar
To make the Navbar sticky, we can simply add the "fixed-
top" class in "Navbar.js" as shown below:

Figure 1.1: Adding the Fixed-top class

Hence, we have successfully created a Sticky Navbar in the


NewsMonkey application.
Fixing Bugs
Issue: Whenever we are fetching the new News by running
the fetch more Date function, then the "setPage" is taking
some time to set the page value, which means taking extra
time in rendering the page while scrolling. This issue occurs
as the "setPage" is an asynchronous function.

Solution: To solve this issue we would add "page+", that is


set page by incrementing the value, in the url. This is so
because the url is being fetched before the set page.

Figure 1.2 Fixing Issues


Changing App.js to Functional
Component
In the previous video, we have successfully changed the
class component of the four components to functional
components. Now, we are going to refactor the "App.js" in
the following manner:
Figure 1.3: Changing App.js to Functional component

Explanation: Firstly, we will render the app in an arrow


function instead of the class. After that, we would use the
'useState' hook to set the progress and the initial state of
progress. Finally, remove the render function from the
"App.js" and also remove the 'this' keyword from the
application.

Result: Hence, we have successfully created the


NewsMonkey application here is a look at the NewsMonkey
application:
Figure 1.4: NewsMonkey Application

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


the upcoming articles, we will be understanding some new
concepts of React by creating some real-life Projects.
Thank you for being with me throughout the tutorial. In the
next tutorial, we will get an Introduction to the MERN stack.
Till then, Keep learning and Keep Coding.

OceanofPDF.com
Introduction to MERN
stack | Complete React
Course Article #41
In the last article, we have completed the NewsMonkey
application by fixing some bugs and refactoring the
application. This time we are going to build an application in
which we will be using our own API and Database. So,
without further ado let’s begin:
Introduction to MERN Stack
MERN stands for MongoDB, Express, React, Node.js, after
the four key technologies that make up the stack.
● MongoDB - It is a document database, which aligns
and works perfectly with javascript.
● Express(.js) - It is a backend web application
framework for Node.js.
● React(.js) - A client-side Javascript framework
● Node(.js) - The premier Javascript web server

Note: We will maintain the backend and the React app


separately. Remember, the node module of the express
application and the react app will not be the same.
Install MongoDB
To install MongoDB, visit the official site of MongoDB. After
that, simply select the community server option available
under the software section of the Navbar. Finally, click on
the download button to get MongoDB.
Figure 1.1: Downloading MongoDB

After downloading, you can simply execute the file and


install MongoDB by selecting the desired options.

So, here we complete the 41st article of this React series. In


the upcoming articles, we will be understanding some new
concepts of React by creating a real-life project with the
help of the MERN stack.

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


next tutorial, we will start Project 3. Till then, Keep learning
and Keep Coding.

OceanofPDF.com
Project 3: iNotebook
backend and React
frontend setup | Complete
React Course Article #42
Till now, we have created the frontend of the two
applications and have used the API for the backend purpose.
Now, we would create our own API with the help of the
MERN stack. Therefore, let’s begin by creating our New
React Application named iNotebook.
Create React App - iNotebook
To create a react app, firstly open Windows PowerShell and
execute the create react app command:
npx create-react-app iNotebook

iNotebook information: This is the name of our new React


application. It is the notebook on the cloud, that is it can be
used to store any notes or important points on the cloud.
This time we will be storing the data on the server. We will
be creating a login Page to grant access to the notes for its
right user only. Hence, we have successfully created the
iNotebook React app.
Creating backend for iNotebook
We would be putting all the files related to the backend, in a
separate backend folder to have a better understanding and
segregation. Open the backend folder with the source code
editor. After that, open the terminal and execute the 'npm
init' command and then fill up some basic details like name,
description, entry point, etc to create a package. Now, we
can install the required framework inside the package.
Installing Express and Mongoose
Express: Express.js is a back-end web application
framework for "Node.js". To install express, simply execute
the below command in the terminal:
npm i express

Mongoose: Mongoose is an extraction layer on top of


MongoDB, which would help us to connect with the Node Js.
It requires a connection to a MongoDB database. It provides
a straightforward, schema-based solution to model the
application data. To install Mongoose, execute the below
command in the terminal:
npm i mongoose

Note: We would install many more packages later on this


React Course. Make sure to create an "Index.js" file, which
would be the entry point of our application.
ThunderClient
It helps in testing the APIs. For example, Below we have
sent a request in the https://www.thunderclient.io/welcome
API and have got a response from the API. Now, we can use
this response in the application. To use it, We can simply
install the thunderclient extension in vscode.
Figure 1.1: Using ThunderClient

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


In the upcoming articles, we will be enhancing the
iNotebook application. In addition to this, we would be
creating endpoints, components, understanding mongoose,
and much more.

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


next tutorial, we will setup iNotebook DB & Express Server.
Till then, Keep learning and Keep Coding.

OceanofPDF.com
iNotebook db & Express
Server Setup | Complete
React Course Article #43
In the previous article, we created the backend of iNotebook
application. In This, we will perform the MongoDB and
Express setup in the application. So, without any further ado
let’s begin!
Working with Backend
Open the backend folder in your source code editor. We
have already installed express and mongoose packages in
the application. Now, let’s install the Nodemon package and
begin working with MongoDB and Express.
Installing Nodemon
Nodemon allows us to develop node.js-based apps, by
automatically restarting the node application when file
changes are detected in the directory. You can install the
nodemon package in the application as a dev dependency
by using the below command:
npm i -D nodemon

MongoDB compass
In the previous video, we have installed MongoDB as a
service and have provided a specific data directory for the
storage. MongoDB compass provides a Graphical user
interface(GUI) to a client, which helps in interacting with the
MongoDB database management system. Some, of the
useful features of MongoDB compass, are mentioned below:
Features of MongoDB compass
● It visualizes and inspects the data, which is stored in
your database
● It creates databases and allows you to insert, update,
and delete data in your database
● It provides real-time server statistics.
● It provides a great way of Managing your indexes
Connecting to a Database
Mongoose requires a connection to the MongoDB database.
Therefore, open the MongoDB Compass app and select the
‘Fill in connection fields individually’ option. Now, you can
Specify the Hostname and the port in which your MongoDB
server is running. After that click on connect.

Figure 1.1: Filling up the fields

Hence, you are successfully connected to your MongoDB


server. After doing this, you will see a list of databases and a
set of options, which will allow you to create and delete
databases.

Figure 1.2: Connected to a Database

After this, you can disconnect to the database and can copy
the connection string and paste it in Mongoose to build the
connection between Node.js and MongoDB. The next step
will teach you about how you can connect MongoDB and
Node.js with the help of the above database URL.
Connect MongoDB with Node.js using
Mongoose
In this subsection, we will be connecting MongoDB with
Node.js by using mongoose.
Figure 1.3: Connect MongoDB with Node.js

To connect MongoDB with Node.js, you have to configure the


code as shown below-

const mongoose = require('mongoose');


const mongoURI = "mongodb://localhost27017/?
readPreference=primary&appname=MongoDB%20Compass
&directConnection=true&ssl=false"
const connectToMongo = () => {
mongoose.connect(mongoURI, () => {
console.log("Connected to Mongo Successfully");
})
}
module.exports = connectToMongo;

Explanation: Here, we have firstly created a db.js file in the


root folder of the application. After that, we have required
mongoose in the application. In the second line of code, we
have set the MonogoURI equal to the Connection String,
which we have copied earlier. In the end, we have created a
‘connectToMongo’ function and have used the
mongoose.connect function inside it and have exported the
connection successfully. Remember, we have used the
common js modules instead of ES6 modules
Result: As a result, we can use the db.js file in multiple files
by including them with require() the module.
Use Node.js MongoDB Connection
Script - Index.js
We would like to use the db.js file in routes/index.js,
therefore we would include it by adding the below code in
Index.js:

const connectToMongo = require('./db');


connectToMongo();

Express Server Setup

Moreover, we would like to make the index.js an express


server of the application. To do so simply copy the below
code in the application:
In Index.js

const connectToMongo = require('./db');


const express = require('express')
connectToMongo();
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('Hello harry')
})
app.listen(port, () => {
console.log(`Example app listening at
http://localhost:${port}`)
})

Result: After doing this, we are successfully connected to


MongoDB.
Testing the API
As you know, we would be using Thunder Client in this
course for testing the APIs. So, let’s enter the URL in
Thunder Client and check for the response of the endpoint.
Thunderclient will respond to the request as shown below.

Figure 1.4: Response of the Endpoint

Here, we are getting ‘hello Harry’ as a response, which


proves that our endpoint is working perfectly.

Hence, we have successfully created a .get endpoint that is


returning Hello Harry.
So, here we complete the 43rd article of this React series. In
the upcoming articles, we will be understanding some new
concepts of React and would be adding a few more
endpoints in the application.

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


next tutorial we will be Creating Routes & Schema for
Storing Notes & Users. Till then, Keep learning and Keep
Coding.

OceanofPDF.com
Creating Routes & Schema
for Storing Notes & Users |
Complete React Course
Article #44
In the last article, we have restructured our react application
and have successfully set up Express and MongoDB in our
app. In today’s video, we will create Routes and Models for
iNotebook applications. So, without further ado let’s begin:
Creating Routes
We can create all our routes in "Index.js", as we have done
in the previous video. For example: we can add three routes
such as Login, Sign up, Home route as shown below:

Figure 1.1: Creating Routes

But, this method will lead to the distortion of the file


structure of our React Application. As a result, maintaining a
large React app will be a nightmare for you. Therefore, we
won’t recommend you to use this method for large
applications.
Structure of iNotebook Application
Here is the folder structure for our iNotebook application.
We would be creating all the models and route files inside
the specific folders to have a better management of our
application.
Creating Mongoose Models
We are creating a Models folder to store the Mongoose
Models. A Mongoose model is a wrapper on the Mongoose
schema. A Mongoose schema defines the structure of the
document, default values, validators, etc., whereas a
Mongoose model provides an interface to the database for
creating, querying, updating, deleting records, etc.
Getting Started
We have already connected the Mongoose with the
database in the previous video. Thus, we would simply
create a model. For example - "Notes.js" and "User.js".

In User.js:
The "user.js" model will contain info about the user. Now, we
would be creating a schema for the user in the following
manner.

const mongoose = require('mongoose');


const UserSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
},
});
module.exports = mongoose.model('user', UserSchema);

Explanation: Above, we have added some of the common


fields, such as Name, Email, Password, Date, etc in the
schema. We have also added the data types for the given
fields and have made some of the fields compulsory to be
entered by the user. In the end, we have exported the
schema. Hence, we can use the above schema in the routes.

In Notes.js:
Notes.js model will be containing all the Notes of the
iNotebook application. Therefore, let’s build a NotesSchema
for it in the following manner.

const mongoose = require('mongoose');


const NotesSchema = new Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true,
},
tag: {
type: String,
default: "General"
},
date: {
type: Date,
default: Date.now
},
});
module.exports = mongoose.model('notes', NotesSchema);

Explanation: Above, we have added some of the common


fields, such as Title, Description, Tag, etc in the schema. We
have also added the data types for the given fields and
have made some of the fields compulsory to be entered by
the user and have provided some of the fields with a default
value. In the end, we have exported the schema. Hence, we
can use the above schema in the routes as well.
Creating Routes
We are creating a Routes folder to store all the routes of the
iNotebook application. After that, We would be linking the
routes with the help of app.use as shown below

Figure 1.2: Creating auth and Notes routes


We have added the "auth" and "Notes" routes. Thus, we are
going to create two files named "auth.js" and "notes.js".

In auth.js:

We would be using the router inside the "auth.js" file. Here’s


how we are going to do that:

Figure 1.3: In auth.js

Explanation: Above, we have imported the express router


in auth file. After that we have used the router.get to specify
the endpoint for a particular route. Here, we have passed
the JSON to the router to display for a specific endpoint of
the appplication.In the end, we have exported the router.
Remember, we have passed the JSON just for the demo
purpose. In the similar fashion, we can create a Notes.js
route.

Result: Hence, the JSON is rendered in the application for a


specific routes as shown below:
Figure 1.4: Results

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


the upcoming articles, we will be creating some useful
endpoints, such as Login, signup, Notes fetch, Notes delete,
etc, for our react application.

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


next tutorial we will be Storing Data into the Database Using
Mongoose Model. Till then, Keep learning and Keep Coding

OceanofPDF.com
Storing Data into the
Database Using Mongoose
Model | Complete React
Course Article #45
Earlier, we learned about Mongoose Model and routes by
adding them to our iNotebook application. In today’s video,
we would be learning how to store data into the Database
using Mongoose Model. So, without further ado let’s begin:
Middleware
They are the functions that have access to the request and
response object in the request-response cycle. They are
used to alter res and req objects for some specific tasks. We
have to use the middleware before using the req.body
command. So, let’s add the middleware in "Index.js" by
writing the below code:
app.use(express.json())

Note: We will be discussing middleware in detail in the


upcoming articles.

res.send(): It is used to Send a string response in a different


format like XML, plaintext, etc. For example, we can send
Hello, plain text, using res.send to /api/auth endpoint.
Figure 1.1: Sending 'hello' as a response

req.body: It holds parameters that are sent up by the client


as a part of the Post request. By default, its value is set to
be undefined and hence it is populated with the help of
middleware. For now, we are extracting the req.body values
in the terminal by using the console.log() command. At this
moment it is undefined as shown below:
Figure 1.2: Using req.body

In auth.js:

Now, we would be learning how to send data to the request


body. In our case, we would be sending data of a specific
user in the request body.
Creating User
We are entering some random data of users in the request
body as shown below:
Figure 1.3: Creating a Random user in request Body

Result: Hence, we have gotten the following details printed


on the console. This means that we are able to read the
req.body properly as well as we are able to send 'hello' as a
response by using res.send.

Figure 1.4: Result- Req.body is working properly


Now, if we send the req.body as a response by using the
res.send then we would be able to get the data as a
response as shown below:

Figure 1.5: Send req.body as a response


Saving the Data in Database
Firstly, Import the user from the model folder in your auth.js.
After that, create a user and use the save function as shown
below. The save() function is used to save the document
data into the database. Remember, To import schema in
your User.js model before performing the above step.

Figure 1.6: Using the save function


Result: Now, our user would be saved in our MongoDB
Database with a different ID as shown below:
Figure 1.7: Data is Stored in the Database

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


the upcoming articles, we would be performing checks to
validate the data entered by the user as well as we would
be creating some more useful endpoints for our react
application.

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


next tutorial we will be Adding Data Validation Using
express-validator. Till then, Keep learning and Keep Coding.

OceanofPDF.com
Adding Data Validation
Using express-validator |
Complete React Course
Article #46
In the previous article, we have seen how to enter data into
the Database. In this article, we would be performing
validation checks for the entered data with the help of
Express Validator Package. So without further ado let’s
begin:
Installing express-validator
To install the express validator package, you have to simply
run the below lines of code in your terminal :
npm install --save express-validator

Using express-validator
After installing this package, let’s understand how to use it
in our iNotebook application. Firstly, we have to import
express validator in our auth.js file by writing the below
piece of code:
const { body, validationResult } = require('express-
validator');

Adding Validation Checks


Now, we would add validation checks for Email, Name,
Password as shown below. Here, we have set the minimum
character length of the name as '3' and that of password as
'5'.
Figure 1.1: Adding validation checks
Error page
Now, If an error occurs in the value then we would like to
inform the user about his/her mistake by showing an error
page. To do so edit the router.post as shown below:
router.post('/', [
body('name').isLength({ min: 3 }),
body('email').isEmail(),
body('password').isLength({ min: 5 }),
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
res.send(req.body);
})
module.exports = router

Explanation: In the above code, we have set that if


error.empty didn’t return a true value, then show a 400 bad
request error and send the specific errors details.
Checking if Validation is Working
For demo purposes, we are sending some invalid values like
the ‘Empty name’ field value. Here’s the result after
entering the invalid data:

Figure 1.2: Checking if Validation is working

In a similar fashion, we can send some more invalid values


to check the working of our validation.
Adding a Custom Message
At this moment, an 'Invalid' message is shown to the user if
the entered data didn’t meet the predefined conditions.
However, we can add a custom message so that the user
can know his/her mistake and can fix it. You can add the
custom message as shown below:
Figure 1.3: Adding a Custom Message

Explanation: Above, we have added a custom message for


Name, Email, Password as 'Enter a valid Name', 'Enter a
valid Email' and 'Password must be at least 5 characters
respectively. Now, if any invalid data is entered in these
fields then the custom message error will be shown to the
user instead of the default 'Invalid' text.
Result: Hence, we have successfully added the validation
layer for the desired fields of the Application.
Creating User
Now, we would be creating the user of the Mongoose model
by writing the below piece of code instead of the save
function, which we have used earlier to store data into the
Database.

User.create({
name: req.body.name,
email: req.body.email,
password: req.body.password,
}).then(user => res.json(user));
Saving the Data into the Database
Now, let’s try to add the data of a legit user in our Database
by adding genuine values in the Name, Email, Password
fields as shown below.

Figure 1.4: Entering Genuine Values

Result: Thus, the data is being saved in the MongoDB


database as shown below:

Figure 1.5: Data is being Stored in Database


Two Entries with One email - issue
Fixation
There’s one more issue with our validation, that is if the user
submits the request two times with the same ‘Name’ and
‘Email’ then the two different entries of Data are stored in
the database. This means that we are not getting the
unique email for each submitted data.
Solution: To resolve this issue, we would firstly open the
db.js and would specify a database, suppose iNotebook. In
our user.js we would create a user variable and user indexes
as shown below:

const User = mongoose.model('user', UserSchema);


User.createIndexes();
module.exports = User

Result: Now, the data of a specific user is stored in an


iNotebook folder. After submitting the data once, we are
unable to add the data of the user with the same email id as
shown below:

Figure 1.6: Unable to register with the same email-id


Response - While entering a
registered ID
Here, we are noticing that whenever someone tries to
register with the same email id then no response is shown
to the user. Now, to make it more appealing we can show a
custom message to the user by sending a response JSON as
shown below:
Figure 1.7: Adding Response for the Error

Result: Here’s the result of applying the above set of code.


Now, In our database, every user has a unique email id.

Figure 1.8: Result

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


the upcoming articles, we would be creating some more
useful endpoints for our react application. In addition to this,
we would be learning about Password Hashing, salt &
Pepper, and much more.

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


next tutorial we will be Creating ThunderClient Collections to
Manage Requests. Till then, Keep learning and Keep Coding.
OceanofPDF.com
Creating ThunderClient
Collections to Manage
Requests | Complete React
Course Article #47
In the last articles, we have added validation to check the
Data in the iNotebook application. In this article, we would
be learning how to create collections in Thunderclient and
also we would be performing some refactoring of the code
to make it more appealing. So, without further ado let’s
begin:
Refactoring the Code
Earlier, we were providing the same response to the client
for any kind of error. But, now we would like to show the
particular error to the user to provide him/her a better
understanding of the issue. To do this, we can simply use
the catch error method.

catch (error) {
console.error(error.message);
res.status(500).send("Some Error occurred");
}
Copy

Adding Comments and Validation


Now, we would add some comments in our 'auth.js' to make
the code more understandable. Here, we are using the
async and await function with some more lines of codes for
validation of the unique email id as shown below:
Figure 1.1: Validation for Unique Email

Explanation: Above, We have used the 'findone' method


on the model, to search and list the user with the email as
'req.body.email', that is the user with this ID already exists
in the database. "findone()" method is used to return a
single document that satisfies the specified query criteria.
Moreover, we have set that if the user with the email ID
already exists then return a '400 bad request' with a custom
message.
Thunderclient Collections
It is a collection of endpoints that are connected with the
application. We can easily manage all the endpoints with
the help of thunderclient collections.
Getting Started
We would create an iNotebook collection in the
Thunderclient. You can do so by opening the collection
option in thunderclient and then selecting the drop-down
menu and adding a 'NewCollection'.

In iNotebook collection:
We would create a new folder named 'authentication' inside
the iNotebook collection. Inside the authentication folder,
we would be creating a new request named 'create a new
user'. Moreover, We would post a request at the
'/api/auth/createUser' endpoint and would again simply add
a request body for validation.

Figure 1.2: Result

Result: Since the user with this email existed we are


thrown with the error. However, if the user enters with the
unique email id then the data is added to our iNotebook
database, as we have already seen.

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


the upcoming articles, we would be creating some more
useful endpoints for our react application. In addition to this,
we would be creating a login facility for the user with the
help of JWT authentication.

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


next tutorial we will be Understanding Password Hashing,
Salt & Pepper. Till then, Keep learning and Keep Coding.

OceanofPDF.com
Understanding Password
Hashing, Salt & Pepper |
Complete React Course
Article #48
Earlier, we have learnt about thunder client collections and
data validation. In this article, we would be learning an
important concept related to the security of our iNotebook
application. So, without further ado let’s begin:
Getting started
Suppose, you are a user and have stored some crucial notes
in the iNotebook Database of the website. Now, if your
'userName' and 'Password' are stored within the database,
then any hacker or a person with some malicious intention
can hack your profile and can easily access your system. To
overcome this issue, we never store the password in the
database. Here’s a brief ray diagram for your better
understanding.
Figure 1.1: Database hacked Scenario
Understanding Password Hashing
The client interacts with the backend and would submit the
username and password detail to the backend for validation.
Now, the backend will decide whether to grant access to the
database or not.
Password Hashing
Hashing turns your password (or any other piece of data)
into a short string of letters and/or numbers with the help of
an encryption algorithm. Hash is a one-way function.
Whenever the user enters the UserName and password,
then in the backend the password is converted to hash to
make it out of sight. This means that the backend will
generate a random output string(hash) which will be
matched with the existing hash in the database for
validation. Now, if the Hash is exactly matched then the
backend will grant access to the client otherwise not.

Figure 1.2: Password Hashing

Result: As a result, if the hacker hacked the database then


still the hacker will only get the 'UserName' and the
'Password Hash', not the actual password. Remember the
Password Hash cannot be converted to the original
password string. Ultimately, the hacker won’t be able to do
anything with the 'UserName' and 'Password Hash'.
Limitation of Password Hashing
Now, what if a pro hacker already has a table (Rainbow
table) having the hash of the most common password.
Then, if the hacker gets the password Hash then he/she can
look in the rainbow table to match the hash with the original
password. For example, a client has a password
‘123456789’ and its hash is ‘1@1bd’ then if the hacker gets
the hash, he/she can easily look in the rainbow table to find
a matching password. Hence, the hacker can easily access
the user database. To overcome this issue we would
understand the concept of salt.
Figure 1.3: Rainbow Table
Understanding Salt
Salts help us mitigate hash table attacks by forcing
attackers to re-compute them using the salts for each user.
This simply means that the backend would add some more
characters(salt) to the password to generate a completely
different password Hash. Remember, Salts are stored in the
Database. We can add more security to the application by
adding pepper. It can be considered as a second salt. That is
another input to change the hash outcome completely. Yet,
unlike salt, it's not stored in the database along with the
hashes. This simply means that Hacker will not be able to
match the password and Hash in the rainbow table.

Figure 1.4: Understanding Salts in Password hashing


Later, We would be adding Password Hashing, Salt & Pepper
in the iNotebook application. Luckily, we don’t have to build
them from scratch as NodeJs provide a package, bcryptjs, to
help us to resolve these issues.

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


the upcoming article, we would be creating a login facility
for the user with the help of JWT authentication. In addition
to this, we would be learning how to use password hashing
in the application practically.

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


next tutorial we will be Hashing Passwords using bcryptjs in
NodeJs. Till then, Keep learning and Keep Coding.

OceanofPDF.com

You might also like