Master ReactJS Part 3 MFurqan Riaz
Master ReactJS Part 3 MFurqan Riaz
Legal Notice:
Disclaimer Notice:
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
})
}
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:
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:
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:
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.
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"
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.
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:
Changing Spinner.js:
Changing NewsItem.js:
Changing News.js
News.defaultProps = {
country: 'in',
pageSize: 8,
category: 'general',
}
News.propTypes = {
country: PropTypes.string,
pageSize: Proptypes.number,
category: PropTypes.string,
}
Changing componentDidMount
useEffect(() => {
updateNews();
}, [])
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:
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
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
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.
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
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:
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.
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.
In auth.js:
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())
In auth.js:
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');
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.
catch (error) {
console.error(error.message);
res.status(500).send("Some Error occurred");
}
Copy
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.
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.
OceanofPDF.com