[go: up one dir, main page]

0% found this document useful (0 votes)
131 views40 pages

Master ReactJS Part 6 MFurqan Riaz

The document discusses adding alerts to the login, signup, and notes components of the iNotebook application. It describes recalling the show alert function, adding the show alert function to App.js, and calling the function from other components to display success, error, and warning messages.

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)
131 views40 pages

Master ReactJS Part 6 MFurqan Riaz

The document discusses adding alerts to the login, signup, and notes components of the iNotebook application. It describes recalling the show alert function, adding the show alert function to App.js, and calling the function from other components to display success, error, and warning messages.

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/ 40

© 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
Adding Login Component to
iNotebook | Complete React
Course Article #69
In the earlier articles, we have seen how to add, update and
delete a Note from the Frontend as well as the backend of
the iNotebook application. Moreover, we have fixed some
major and minor issues in our iNotebook application. In
today’s article, we will be adding the Login and SignUp
functionality to maintain the privacy of the user in the
iNotebook application. So, without further ado let’s begin!
Adding the Login and SignUp Buttons
First of all, we would like to add a login and Sign Up section
to the Navbar of the application. To do that, we will add two
Bootstrap buttons in the Navbar component as shown
below:

<Link className="btn btn-primary mx-1" to="/login"


role="button">Login</Link>
<Link className="btn btn-primary mx-1" to="/signup"
role="button">signup</Link>

Creating a Login and SignUp


component
Now, we will create a login and Sign Up component with a
Bootstrap form inside them. Moreover, we will render the
signup and login components whenever the client clicks on
the signup or login button respectively. Here’s how we can
do that:

<Route exact path="/login">


<Login/>
<Route exact path="/signup">
<Signup/>

Explanation: First of all, we will create a login.js and


signup.js component. After that, we will import the login and
Sign Up component in App.js. Hence, the Signup and login
components are rendered in the application on navigating to
the specific route respectively.
Adding Form to Components
Now, we will add login and sign up forms to the newly
created components. Moreover, we will add the functionality
such that the client won’t be able to access the Homepage
of the iNotebook application if the auth token isn’t valid.
Let’s begin working with the Login component in this article.
Validating the Login User
If you remember, we have earlier created a Login endpoint
in the authentication section of the iNotebook collection in
thunder client. Remember, we will hit this endpoint after the
submission of the Login Form to validate the user from the
backend of the application.
Getting Started
First of all, we will add and enhance our desired bootstrap
Form in the Login component. Moreover, we have added a
‘handle submit’ function to the onSubmit event of the form.
Subsequently, we will be creating the handle submit
function to hit the login endpoint with the Fetch API.
Using the Fetch API
In the fetch API, we will be using the login endpoint URL as
the first parameter. Consequently, we will be using the
‘POST’ method as a request and have passed content type
in the header. Remember that the body consists of the Email
and Password as shown below. Finally, the response object
from the fetch will contain information about the response
object itself.

Figure 1.1: Creating the HandleSubmit Function


Applying the UseState Hook and
Onchange Function
Now, we will be using the ‘useState’ hook in the login.js to
change the state of ‘email’ and ‘password’. Remember, we
have passed the email and the password to the value event
of the buttons of the Login form. In addition to this, we are
using the ‘Onchange’ function to set the credentials, that is
to set the email and password.
Figure 1.2: Applying the UseState Hook and OnChange
Function
Result: Hence, after submitting the login form we are
getting the authoken as shown below:

Figure 1.3: Result - Getting the Authtoken


Redirecting the User
After getting success, in the above procedure, we will save
the auth token and redirect the client to the Homepage
otherwise we will show an alert of ‘invalid credentials’ to the
user as shown below:

Figure 1.4: Redirecting the User


Explanation: Here, we have saved the token in the
LocalStorage and have used the ‘UseHistory’ hook to
redirect the client to the homepage. Make sure to import the
use history hook from the react-router-dom.

Result: Hence, after submitting the form with the correct


credentials, the user will be redirected to the Home page of
the iNotebook application.

So, here we complete the 69th article of this React course.


In the upcoming articles, we will be adding the SignUp
functionality in the iNotebook application. In addition to this,
we will be understanding some amazing concepts of React.

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


next tutorial we will be Adding SignUp Component to
iNotebook. Till then, Keep learning and Keep Coding.

OceanofPDF.com
Adding SignUp Component to
iNotebook | Complete React
Course Article #70
In the previous articles, we have fixed some major and
minor issues in our iNotebook application. Moreover, we
have created and added the login functionality for accessing
the Add Note page of the iNotebook application. In today’s
article, we will be creating and adding the signUp
component in the application. So, without further ado let’s
begin!
Adding a Sign-Up form
First of all, we will add and enhance our desired bootstrap
Form in the SignUp component. Here, we will be adding the
Name, Email, Password and Confirm Password field in our
SignUp form. Moreover, we have added an ‘Onchange’
function to the onChange event of the form as shown below:

Figure 1.1: Adding the Sign-Up Form


Getting Started
If you remember, we have earlier created a create user
endpoint in the authentication section of the iNotebook
collection in thunder client. Remember, we will hit this
endpoint after the submission of the SignUp Form to create
the user in the backend of the application. Now, we will
perform the similar steps, as we have done while creating
the Login Component as discussed below.
Adding the HandleSubmit Function
As we have discussed earlier, In the fetch API, we will be
using the Create User endpoint as the first parameter.
Consequently, we will be using the ‘POST’ method as a
request and have passed content type in the header.
Moreover, we are using the destructuring method of
javascript to get name, email, password, from the
credentials and we are passing them in the body as shown
below. Finally, the response object from the fetch will
contain information about the response object itself. In
addition to this, we are using the ‘useState’ hook in the
Signup.js to change the state of name, email, password, and
cpassword as shown below:

Figure 1.2: Creating the HandleSubmit Function


Redirecting the User
After getting success, in the above procedure, we will save
the auth token in the local storage and will use the
‘Usehistory’ hook to redirect the client to the Homepage.
Otherwise, we will show an alert of ‘invalid credentials’ to
the user as shown below:

Figure 1.4: Redirecting the User

Result: Hence, we have successfully added the login and


SignUp functionality to the iNotebook application.

So, here we complete the 70th article of this React course.


In the upcoming articles, we will be adding alerts to the log-
in, Signup & Notes component. In addition to this, we will be
understanding some amazing concepts of React.

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


next tutorial we will be Adding Alerts to Login, Signup &
Notes Component of iNotebook. Till then, Keep learning and
Keep Coding.

OceanofPDF.com
Adding Alerts to Login,
Signup & Notes Component
of iNotebook | Complete
React Course Article #71
In the previous article, we have created the fully functional
Login and SignUp endpoint in the iNotebook application. In
today’s article, we will be adding a proper alert to the login,
SignUp and Notes Component of the iNotebook application.
In addition to this, we will also be adding the alert in the
different functions, such as DeleteNote, AddNote etc, of the
application. So, without further ado let’s begin!
Recall - Show Alert function
If you remember, we have created an Alert component for
our textUtils application. Now, we will use the same alert
component in the iNotebook application.
Adding the ShowAlert Function - In
app.js
First of all, we will add a ShowAlert function in App.js as
shown below. Remember, we are using the useState hook of
React to set the State of the Alert.
Figure 1.1: Adding the ShowAlert Function

Explanation: Here, we have passed two arguments in the


object which are ‘message’ and ‘type’. The ‘type’ is actually
the status of our action, like success, warning etc. The
message is the text which will be displayed. Moreover, we
will pass the showAlert function to the Home, Login, Signup
Component of iNotebook as a prop.
Passing the ShowAlert function in
Notes component
You can also create a context for the proper management of
the Alerts in an application. However, In order to make this
application simple, we are trying to add alerts through prop
drilling. Here’s how we can pass the showAlert function from
Home.js to the Notes.js:
Figure 1.2: Passing the showAlert function
Using ShowAlert function in SignUp
Component
In the previous article, we have rendered a custom error
message whenever the client tries to create an account in
the iNotebook application with invalid credentials. However,
this time, we are using the showAlert function to show the
‘error’ or the ‘success’ message to the client for their action
as shown below:

Figure 1.3: Show Alert function in Sign Up Component


Using ShowAlert function in Login
Component
If you remember, earlier, we have rendered a custom error
message whenever the client tries to access the iNotebook
application with invalid details. However, this time, we are
using the showAlert function to render the ‘error’ or the
‘success’ message for the values of the client as shown
below:

Figure 1.4: Show Alert function in Login Component

Result: Now, whenever someone tries to login or Sign Up


into the iNotebook application then, they will be shown an
alert message as shown below:

Figure 1.5: Result - Alert added successfully

Adding the Alert to different


functions
Consequently, we would like to show an alert message while
using the delete, edit and update features of the iNotebook
application. Hence, we have to add the below piece of code
to the respective function.
handleClick function
You might remember that the handle click function has been
assigned to the update Note button, which means this
function is responsible for updating the notes. Therefore, we
will show the alert message after the execution of this
function by adding the below piece of code:
props.showAlert("Updated successfully", "success");

deleteNote Function
Similarly, we will add the below piece of code to show an
alert message on the deletion of the Notes.

props.showAlert("Deleted successfully",
"success")

addNote function
Moreover, we would like to show an alert whenever a new
note is being added to the application. To do so, first of all,
we will pass the showAlert component to the AddNote.js. In
AddNote.js, we will add the below piece of code in the
handleClick function, which is responsible for adding the
Notes in the application.

props.showAlert("Added successfully", "success")


So, here we complete the 71st article of this React course.
In the upcoming articles, we will be adding the logout option
for the logged-in User. In addition to this, we will be fetching
the user-specific notes in the iNotebook application and will
be understanding some amazing concepts of React.

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


next tutorial we will be Fetching User Specific Notes in
iNotebook. Till then, Keep learning and Keep Coding.

OceanofPDF.com
Fetching User Specific Notes
in iNotebook | Complete
React Course Article #72
In the previous article, we have added Alerts to log in,
Signup & Notes Component of the iNotebook application. In
addition to this, we have also added the alert in the different
functions, such as DeleteNote, AddNote etc, of the
application. In today’s article, we will be fetching the User
Specific Notes in iNotebook. So, without further ado let’s
begin!
Getting Started
If you remember, we have hardcoded the authtoken in the
NoteState.js context. Now, instead of hardcoding, we will be
taking the authtoken from the Local Storage. To do so, we
will change all the occurrences of the authtoken in
NoteState context with the following piece of code:

"auth-token": localStorage.getItem('token')

In Notes.js - Redirecting the User


Now, we will add the logic such that if the
localStorage.getItem(‘token’) is not null then, the client will
be redirected to the Homepage of the application.
Otherwise, we will redirect the user to the Login Page of the
application, in order to access the Notes as shown below:
Figure 1.1: In Note.js - Redirecting the User
In Navbar.js - Adding Logout Feature
Now, we would like to remove the login and signup buttons
from the Navbar, if the client is already logged in. To do so,
we will add the logic such that if the
localStorage.getItem(‘token’) is not null then the client will
be shown a logout button in place of the login/signup
button. This is so because, if the
local.storage.getItem(‘token’) is not null then it means that
the user is logged in.

Figure 1.2: Adding Logout Button

Explanation: Moreover, we have added the handleLogout


function to the onClick event of the Logout button.
Therefore, we have to create a handleLogout function in the
Navbar.js as discussed below.
Creating the handleLogout Function
In the handleLogout function, we have added the logic to
remove the authtoken from the Local Storage and have also
redirected the client to the login page. Remember, we are
using the use History hook to redirect the user to the login
page. Here’s how we can do that:

Figure 1.3: Creating the handleLogout function

Result: Hence, we have successfully fetched the User-


specific Notes in the iNotebook application as shown below.
Here, we are logged in with the username and email id of
‘bmehta’. Thus, we are getting the specific notes of
'bmetha' only, and not of other users.

Figure 1.4: Result - User-specific Notes in iNotebook


The task for you: Till now, we haven’t created the about
page of the iNotebook application. Thus, I would expect that
each one of you will try to create an About page by yourself.
In addition to this, you can create an UserAccount page and
you can use your creativity to add some more features to
the iNotebook application.

Hence, we have successfully completed the iNotebook


application.

So, here we complete the 72nd article of this React course.


In the upcoming articles, we will begin understanding
Redux. In addition to this, we will be understanding some
more amazing concepts of React.

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


next tutorial we will get an Introduction to Redux. Till then,
Keep learning and Keep Coding.

OceanofPDF.com
Introduction to Redux |
Complete React Course
Article #73
In the previous article, we have fetched the user-specific
notes in the iNotebook application and have wrapped it up.
In today’s article, we will be having a short introduction to
Redux. Consequently, we will be understanding Redux with
the help of fascinating visuals and an analogy. So, without
further ado let’s begin!
Redux
It is a state management library for javascript applications.
We can use it with React, Angular,Vue.js and vanilla JS. This
is because it is a state management library, therefore it
doesn’t care about which library we are using to build the
UI.
The problem without a State
Management library
Well, if you have ever built an application with a complex UI,
you have probably come across a situation where you need
to keep different parts of the UI synced. In a complex
application, let’s say the user changes data in one part of
the application then other parts of the application should be
immediately updated to reflect the changes. In more
complex scenarios, the data also gets updated as a result of
network requests or background tasks. Therefore, we need
to write a lot of code to keep it synced.
Why Use Redux - State Management
Library?
With the help of Redux, instead of scattering the application
state in various components of the application, we will store
all the application state inside a central repository, that is a
single JS object called the Redux Store. You can assume it as
a kind of database for the front end of an application. So
with this architecture, the different components of the app
have to no longer maintain their own state. Instead, they
get what they need from the Redux store. Redux as an
architecture also makes it easy to understand how the data
changes in our application, if something goes wrong we can
see exactly how, why, when, and where the data changed.
Remember, Redux performs a similar function as Context
API and hence helps in reducing the prop drilling. Hence,
Redux is a custom solution for state management.
In a Nutshell - The Need to Use Redux
● Redux centralizes the application’s state
● It also makes the data flow transparent and predictable
● In addition to this, It also makes Testing very easy.
● It brings out Consistency throughout the application
Actions & Reducers
Actions: An action is a plain object that describes the
intention to cause change. Let’s suppose we are creating an
iNotebook application, which contains a lot of notes. Now,
suppose, we want to change the correspondence of the
notes with respect to their Users. To do so, we will bring an
action to change the Notes array by adding another note.

Reducers: A reducer is a function that determines changes


to an application state. It returns to the new State and tells
the store how to do it. For example, we would like to add a
new note in the application then, Reducer will determine
which variable/array/State will be changed by the addition
of the note. In most simple words, It uses the action it
receives to determine the change.
Figure 1.1: Actions and Reducers

In the upcoming articles, we will understand the actions and


reducers in detail with a practical demo.
The analogy of Actions and Reducers
Let’s suppose that the UI of our application is a child of a
family. Now, this Child asks his/her parents for something
such as a bat and ball. Now, this wish of the child will be
fulfilled by his/her parents, who are action initiators. Let’s
suppose that the parents are busy then they will dispatch a
message to ‘Shankar Doe’, who is the reducer. Hence,
‘Shankar doe’ will actually perform the task of finding what
the child has demanded. This same procedure goes on while
creating an application with the help of Redux.
Figure 1.2: Analogy of Actions and Reducers

So, here we complete the 73rd article of this React course.


In the upcoming articles, we will perform the installation of
the Redux. In addition to this, we will be understanding the
above concepts by creating an application with the help of
Redux.

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


next tutorial we will be Setting up a React Application for
Redux. Till then, Keep learning and Keep Coding.

OceanofPDF.com
Setting up a React
Application for Redux |
Complete React Course
Article #74
In the previous article, we have a short introduction to
Redux. Consequently, we have understood Redux with the
help of fascinating visuals and an analogy. In today’s article,
we will be setting up an application that will help us to
understand Redux efficiently. So, without further ado let’s
begin!
Creating a React App
First of all, we will create a new folder named the Redux app
inside the React Course folder. After that, we will open the
folder in vs code and use the below command to create the
React app:

npx create-react-app .

Adding Bootstrap
After creating the application, we will add some bootstrap
code in the application for the enhancement of the
application. Here, we have created Navbar.js and have
added the Navbar component of the bootstrap. Remember,
to import and use the Navbar component in the app.js.
Hence, the Navbar will be added to the application!
Getting Started - State Bank of Harry
application
For understanding Redux, we are going to create a simple
simulation of a Banking application. In the application, we
will add the functionality of incrementing and decrementing
the amount of money available in the bank.
Adding the 'Your Balance' Button
Firstly, we will add a "Your Balance" button in the Navbar
section of the application. You can add the button by using
the below piece of code:

<button disabled={true} className="btn-


primary">Your Balance: 0</button>

Creating Shop Component


First of all, we will create a Shop component and add a
button in the component as shown below. Make sure to use
and import the shop component in the app.js.

Figure 1.1: Creating Shop Component

Explanation: In shop.js, we have added the heading and


two-button with ‘+’ and ‘-’ signs for incrementing and
decrementing the values respectively. Moreover, we have
enhanced the buttons and the text by adding some basic
CSS.
Result: Hence, the buttons and the text are added in the
React application. Here’s the look of the application.

Figure 1.2: Result - Our Application

So, here we complete the 74th article of this React course.


In the upcoming articles, we will be creating the Redux
store. In addition to this, we will be understanding how to
access the values from the Redux store and use it in the
application.

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


next tutorial we will be Creating a Reducer and Action
Creator in Redux. Till then, Keep learning and Keep Coding.

OceanofPDF.com
Creating a Reducer & Action
Creator in Redux | Complete
React Course Article #75
In the previous article, we have set up a Basic React
Application to help us understand Redux. Moreover, we have
added a bank simulation with the buttons of incrementing
and decrementing the values in the application. In today’s
article, we will be creating the action and reducers to
manipulate the state of the application. So, without further
ado let’s begin!
Getting Started
We are trying to understand Redux by building a simple
banking application. In our case, We would like to increase
the amount when the user clicks on the increment button
and decrease the amount when the client hits the
decrement button.
Installing Redux, React-redux and
redux-thunk
First of all, we will install Redux with some other important
redux libraries and the middlewares. We can easily do so by
using the below piece of code in the terminal:

npm i redux react-redux redux-thunk

Creating boilerplate template


Now, we would like to render the complete state of our
React application in one place. Therefore, we will create a
boilerplate template for that state. In the src folder, we will
create a state folder that will help us in managing the state
of our banking application. Moreover, we will create two
more folders named ‘Action-creators’ and ‘reducer’ in the
state folder. As we have discussed earlier, the action creator
will initiate the action and the reducer is a function that will
help us in changing the state.
Creating deposit/withdraw money
function
Firstly, we will create an index.js file in the action-creators
folder and will create two functions inside it. The first
function is named ‘Depositmoney’, which will increase the
amount of the state. The second function is named
‘Withdrawmoney’, which will decrease our created state.
Here’s how we have created both the functions in index.js:

Figure 1.1: Creating deposit/withdraw function

Explanation: Here, the deposit money function is returning


such a function which have the ‘type’ and ‘payload’ of the
data. Remember, we will be calling this deposit money
function in the upcoming articles. Similarly, we have created
the ‘Withdrawalmoney’ function. Finally, we have exported
both functions from index.js.
Creating a Reducer Function
We will be creating the ‘Amountreducer’ file, which will be
capable of manipulating the amount. In amountreudcer.js,
we have created a reducer function as shown below:

Figure 1.2: Creating a Reducer Function

Explanation: Here, the reducer function is taking state and


action as parameters. In addition to this, we are using the if-
else statement to increment the ‘amount state’ whenever
the action type is ‘deposit’. Similarly, we are using the if-
else statement to decrement the ‘amount state’ whenever
the action type is ‘withdraw’. Moreover, we have returned
the state if both the conditions are false.

So, here we complete the 75th article of this React course.


In the upcoming articles, we will be creating the Redux store
with the help of actions and reducers. In addition to this, we
will be understanding some amazing concepts of React.
Thank you for being with me throughout the tutorial. In the
next tutorial we will be Creating a Redux Store. Till then,
Keep learning and Keep Coding.

OceanofPDF.com
Creating a Redux Store |
Complete React Course
Article #76
In the previous article, we have created the action and
reducers to manipulate the state of the application. In
today’s article, we will be combining all the reducers to work
as a single reducer function. In addition to this, we will be
going to create a Redux store for our application. So,
without further ado let’s begin!
In reducers folder- Index.js
First of all, we will create an index.js file that will combine all
the reducers to work as a single reducer function for the
application.

Figure 1.1: Using the Combine Reducer Method

Explanation: Here, we have imported the


combineReducers and amount reducer in the index.js. In
addition to this, we have exported the combined reducers
having the amount reducer. Make sure that at this very
instance we have only one reducer. However, a combined
reducer function can turn many different reducer functions
into a single reducer function.
Creating the Redux Store
Firstly, We are going to create a store.js file in the State
folder. After that, We will be creating a redux store in this file
as shown below:

Figure 1.2: Creating the Redux Store

Explanation: Here, we are using the create store function


to create a Redux store that holds the complete state tree of
your app. The CreateStore function takes reducers, initial
State, and middleware as a parameter. Hence, our Redux
store is being created successfully. Remember, we are going
to export the action creators from the state to index.js for
better management.

Granting access to Redux Store


Now, We will be granting access to this redux store to our
overall application. To grant access to this redux edit the
index.js as shown below:
Figure 1.3: Granting Access to Redux Store

Explanation: Here, we are importing the provider and the


store in the index.js. The Provider component makes the
Redux store available to any nested components that need
to access the Redux store. Hence, the complete application
has access to the redux store.

So, here we complete the 76th article of this React course.


In the upcoming articles, we will be using the actions and
reducers to make the buttons functional. In addition to this,
we will be understanding some amazing concepts of React.

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


next tutorial we will be Accessing State in Redux. Till then,
Keep learning and Keep Coding.

OceanofPDF.com
Accessing State in Redux |
Complete React Course
Article #77
In the previous article, we have combined all the reducers to
work as a single reducer function. In addition to this, we
have set up a Redux store for our React application. In this
article, we are going to understand how we can access the
State in Redux. So, without further ado let’s begin!
In Navbar.js - Accessing the Amount
State
Now, we will be using the use selector hook in Navbar.js to
access and use a specific state in the Navbar component.
The UseSelector hook allows us to get data from the Redux
store state, by defining a selector function. With the help of
the use selector hook, we can select any state from the
redux store to use it inside any component of our
application. Here’s the way of using the ‘useSelector’ hook:

const amount = useSelector(state => state.amount)


return (
<button disabled={ture} className="btn-
primary">Your Balance: {amount}</button>
)

Result
Hence, we have pulled the ‘amount’ from the created state
in the particular component, with the help of the use
selector hook. Remember, we are using the amount state in
the ‘Yourbalance’ button instead of the custom number. As a
result, the amount will be rendered as the value assigned in
the amount state. In our case, the initial value in the
amount state is 0. Therefore, we are getting the below
result:

Figure 1.1: Result

So, here we complete the 77th article of this React course.


In the upcoming articles, we will be adding the functionality
of incrementing or decrementing the balance to our
respective buttons. In addition to this, we will be
understanding some amazing concepts of React.

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


next tutorial we will be Updating state from a different
component in Redux. Till then, Keep learning and Keep
Coding.

OceanofPDF.com
Updating state from a
different component in
Redux | Complete React
Course Article #78
In the previous article, we have set up a Redux store for our
React application. In addition to this, we have learned how
we can access the state in Redux with the help of the use
selector hook. In today’s article, we are going to understand
how we can alter the state in Redux. So, without further ado
let’s begin!
Applying the useDispatch hook
Now we will dispatch the message from the action creators
to the reducer. In our case, the action creator will dispatch
the payload and type to the reducer, with the help of the
use dispatch hook. Hence, in our shop.js we will make the
below changes:

Figure 1.1: Applying the useDispatch hook


Explanation: Here, we have imported the use dispatch,
action creators, and blindActionCreators in the Shop.js.
Moreover, we are adding an 'onClick' event to the increment
and decrement button. In the onClick event, we are using
the withdraw money action creator in the dispatch function.
As you know, we have already created the withdraw money
action creator in the earlier articles. Similarly, we have used
the deposit money action creator in the on-click event of the
increment button.
Result: Hence, on clicking the increment button the balance
is updated by adding ‘100’ each time. The same goes for
the decrement button of the application.
Applying the Bind Action Creator
Now, we will perform the above task with the help of bind
Action creators to increase the efficiency of the code. Here’s
how we can use the bindActionCreators:

Figure 1.2: Applying the bindActionCreator

Explanation: Here, we have passed the action creators and


the dispatch argument to the bindActionCreator. Now, we
can use the withdraw money or deposit money function
directly in the 'onClick' event as shown above. Bind Action
Creator turns an object whose values are action creators
into an object with the same keys, but with every function
wrapped into a dispatch call so they may be invoked
directly.

So, here we complete this React Course with the completion


of four amazing projects named TextUtils, NewsMonkey,
iNotebook, and StateBank of Harry. If you have watched this
course at this instance, then please leave feedback in the
comment section of the first article of this React course.

This was our last tutorial. Thank you for being with me
throughout the series. Keep learning and Keep Coding.

OceanofPDF.com

You might also like