MERN Authentication Tutorial #10 - Making a useSignup Hook

Net Ninja · Intermediate ·🔧 Backend Engineering ·3y ago

Key Takeaways

This video tutorial demonstrates how to create a custom React hook for handling user sign-up logic in a MERN application, utilizing tools like React, useState, useAuthContext, and the fetch API. It covers creating a reusable hook, sending POST requests to the server, and updating the auth context with user data.

Full Transcript

all right then gang so at the minute we have this sign up form and also the login one but if we try to submit these forms all it's doing is log in the details to the console what we want to do is hit that api endpoint on the back end of our application which is going to sign that user up using these details right here so we're going to create a custom hook in our react application to handle all of that logic all right then so we have this signup component right here and when we click on this button at the bottom to submit the form right here is where we console.log the email and password now ultimately we want to send that post request to the server to handle that sign up so we could put all the logic here but we are going to create that custom hook to do all of that logic and then just use that hook in this component so not inside pages we want to go inside hooks and create a new file called use signup.js and then inside here i need to import a couple of things first of all so i'm going to paste those in we import use state from react since we need some local state and also use auth context and that's from dot forward slash use auth context because it's also a hook inside this folder so it's this one right here and that returns us the context with the user property and also the dispatch function so ultimately what we're going to do is sign up inside this hook we're going to send that request get a response back now if it's successful and the user is logged in then i also want to update that auth context to say look we have the current user now and i can update that user property if we open up the context or context this thing right here with the user's email so we have that available in our application so let's start this hook i'm going to say const and in fact i'm going to export this as well so we can use it in another file export const use sign up and we set that equal to a function like so now in here i'm going to have a few pieces of state and again i'm just going to paste those in to save me typing them out so we have a piece of state for an error if there is an error with the sign up request and also a set error function to change it no to begin with and then also a bit of stateful is loading and setting loading to change that as well which is not to begin with now this is loading piece of state is going to be true when we start the request so if you wanted some kind of loading state or disabled state on your button in the form when we start to send that request we can use this piece of state so let us now create a function inside here called sign up so const sign up is equal to a function and it's going to be an async function and inside this function we're taking the email and password that the user wants to sign up with all right so what do we want to do inside here well first of all we want to set is loading to be true so set is loading and that's going to be true because we're just starting the request and also we're going to reset the error to be null every time we make a signup request because imagine this i know it's not to begin with but then we might make a request to sign up and there might be some kind of error and we set the error then when we make a subsequent request if we try to correct those errors at the start of that request we want to reset the error to be null because we don't want to always show the error if they try to rectify it so we reset it at the start all right and now we need to make that post request so const we get a response and we set it equal to a weight and we're using the fetch api and inside here the end point is going to be forward slash api forward slash user forward slash sign up now by the way i'm not using localhost port 4000 right here because if you take a look inside the package.json we use this proxy right here so if i just use forward slash like this it's going to proxy it to localhost port 4000 and that also gets rid of any kind of cause error as well all right so we have this fetch request right here but it is a post request so we need to pass in some options and we need to say that the method is going to be post and also we need to pass in some headers so headers and the headers in this case is going to be the content hyphen type which will be set to application forward slash json so that's the type of data we're sending with the request and the data itself is on the body property and we want to pass in the email and password as an object but in json format so we say json.stringify to turn it into a json string and then pass in an object with the email and password like so so that is the request right here so then when we get a response in order to get the json data we have to use response.json a method called json on this and that is an asynchronous method so we say const json is equal to response dot json now remember by the way we need a weight here because it's asynchronous this thing this is either going to return to us some information with the json web token if it was a success but if it wasn't a success then it's going to send us back an error message instead okay now this response has an okay property as well and if we send back an error status code like 400 then okay is going to be false so we can check for that we can say if not response dot okay so if it's not okay if there's a problem then what we want to do is set is loading to be false because now we're no longer loading and then also set the error to be the json.error because we get an error property back when there is an error okay now then if the response is okay so if response dot okay then what we want to do is three things basically we want to update the auth context with the user email that we get back so we're storing the email in this user property so we need to use a dispatch and the action is gonna be login and we also need to update the loading state to be false again because we're finished and also i want to take the json web token that we get back and i want to store that somewhere in the browser so that if the user closes the browser and opens the browser back up again and goes onto our website they still have that json web token in the browser stored for that user so they're logged in still and the way we're going to do that is by saving it to local storage so let me do a comment first of all to say save the user to local storage and it's just going to be the json web token and the email property remember so this whole json object so i'll say local storage dot set item this is how we set a new item i'm going to call the item user and it's going to be jason dot stringify and then the json response we get back here which is actually an object so we're re-string define it into json again because we have to store strings inside local storage so now we have a json version of that object and on it we have the json web token that we get sent back and also the email property because remember if we go to the back end over here inside the controllers user controller right here for sign up user we send back the email and the token so we're storing both of those in local storage so that's the first thing we want to do the next thing we want to do is update the auth contacts now for this we're going to use the use auth context hook right here so let me grab that and i'm going to say const and we want the dispatch function from this so we set that equal to use auth context so we grab that dispatch function and we need to dispatch now some kind of action so let's do that we say dispatch the type of the action is going to be login so that the login case fires right here and the payload the action payload is going to be basically the user we get back so it's going to be this json right here or it could be the json email it doesn't really matter so let's say the payload is just the json oops not in capitals so we'll say payload is the json that we get back and then finally we want to set is loading to be false again all right and that's pretty much it we do need to return this function at the bottom so that we can grab it from this hook so let's do that right here return and it's going to be the sign up function but also we want to return is loading and also the error just in case there is one so we can grab all of these three things from this hook all right cool so that is the hook pretty much done now we can go ahead and use it inside the sign up component all right then so first of all inside this component i want to import that use sign up hook all right and then we want to invoke that and grab those three things from it so we say const we want the sign up function we want the error if there is one and also is loading and we set that equal to use sign up like so so we have access to these three things now down here instead of logging the information to the console we want to await the sign up function and we pass in the email and password which are being stored in our state so whatever a user types into this form and that's all there is to it right there but we can also use error and is loading so what i'll do is output the error at the bottom if there is one so i'll say error and then double ampersand and then i'm going to do a div and that's also going to have a class name equal to error for standing purposes and then inside here we'll pass the error like so so that's the error and also i want the button to be disabled if is loading right here is true because if is loading is true a request is going on we don't want to send another one right away so i'll say disabled is equal to is loading and that's pretty much it that's all we need to do for now so now let's save this cross our fingers and see if this works so then what i want to do now is just quickly refresh i'm going to try signing up with someone that already exists so yoshi at netninja.dev and then i'm going to do the password as abc capitals lower abc one two three and exclamation so the password is correct the email is correct they already are signed up so we should get an error so sign up and we can see email already in use all right so let's try someone who's not been signed up yet so i'm going to say toad net ninja.dev and then for the password i'll just say abc sign up password not strong enough awesome so we'll say abc upper abc lower one two three and exclamation sign up and now you can see this auth context state changed because we did that dispatch and now the user is right here and we have this email property on it and also the token now also because when we refresh this token isn't going to be in the application because the state kind of resets and starts null but we have we saved it to local storage so if we go to application and local storage we can also see this user property over here and we see the json string with the email and the token in local storage as well now if we refresh that's still going to be here so we can grab it from local storage even though in the console the auth context date is now null we will address this issue later on as well whereby when we first load the page we look to see if we have this token over here and if we do we update the local state but for now this is null but we know the user is still technically logged in because we have this user thing right over here with the web token all right so that is the use signup hook done next we're going to do it for logging in as well we're going to create a custom hawk to log users in

Original Description

In this MERN auth lesson, you'll create a custom, reusable React hook that we can use to sign new users up to the application. ⭐⭐ Get the full course now (without ads) on the Net Ninja Pro site: https://netninja.dev/p/mern-auth-tutorial/ ⭐⭐ Get access to all free & PREMIUM courses on Net Ninja Pro: https://net-ninja-pro.teachable.com/p/net-ninja-pro/ 🐱‍💻 Access the course files on GitHub: https://github.com/iamshaunjp/MERN-Auth-Tutorial 🐱‍💻 MERN Stack Tutorial: On Net Ninja Pro - https://www.youtube.com/watch?v=2liZ3uvO9bs On YouTube - https://www.youtube.com/watch?v=98BzS5Oz5E4&list=PL4cUxeGkcC9iJ_KkrkBZWZRHVwnzLIoUE 🐱‍💻 React Tutorial: On Net Ninja Pro - https://codinginpublic.dev/projects/parallax-landing-page/ On YouTube - https://www.youtube.com/watch?v=j942wKiXFu8&list=PL4cUxeGkcC9gZD-Tvwfod2gaISzfRiP9d 🔥🔥🔥 Other resources: VS Code - https://code.visualstudio.com/ MongoDB Atlas - https://code.visualstudio.com/
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Net Ninja · Net Ninja · 0 of 60

← Previous Next →
1 Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Net Ninja
2 Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Net Ninja
3 Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Net Ninja
4 GraphQL Tutorial #1 - Introduction to GraphQL
GraphQL Tutorial #1 - Introduction to GraphQL
Net Ninja
5 GraphQL Tutorial #2 - A Birdseye View of GraphQL
GraphQL Tutorial #2 - A Birdseye View of GraphQL
Net Ninja
6 GraphQL Tutorial #3 - Project (stack) Overview
GraphQL Tutorial #3 - Project (stack) Overview
Net Ninja
7 GraphQL Tutorial #4 - Making Queries (front-end preview)
GraphQL Tutorial #4 - Making Queries (front-end preview)
Net Ninja
8 GraphQL Tutorial #5 - Express App Setup
GraphQL Tutorial #5 - Express App Setup
Net Ninja
9 GraphQL Tutorial #6 - Setting up GraphQL
GraphQL Tutorial #6 - Setting up GraphQL
Net Ninja
10 GraphQL Tutorial #7 - GraphQL Schema
GraphQL Tutorial #7 - GraphQL Schema
Net Ninja
11 GraphQL Tutorial #8 - Root Query
GraphQL Tutorial #8 - Root Query
Net Ninja
12 GraphQL Tutorial #9 - The Resolve Function
GraphQL Tutorial #9 - The Resolve Function
Net Ninja
13 GraphQL Tutorial #10 - Testing Queries in Graphiql
GraphQL Tutorial #10 - Testing Queries in Graphiql
Net Ninja
14 GraphQL Tutorial #11 - GraphQL ID Type
GraphQL Tutorial #11 - GraphQL ID Type
Net Ninja
15 GraphQL Tutorial #12 - Author Type
GraphQL Tutorial #12 - Author Type
Net Ninja
16 GraphQL Tutorial #13 - Type Relations
GraphQL Tutorial #13 - Type Relations
Net Ninja
17 GraphQL Tutorial #14 - GraphQL Lists
GraphQL Tutorial #14 - GraphQL Lists
Net Ninja
18 GraphQL Tutorial #15 - More on Root Queries
GraphQL Tutorial #15 - More on Root Queries
Net Ninja
19 GraphQL Tutorial #16 - Connecting to mLab
GraphQL Tutorial #16 - Connecting to mLab
Net Ninja
20 GraphQL Tutorial #17 - Mongoose Models
GraphQL Tutorial #17 - Mongoose Models
Net Ninja
21 GraphQL Tutorial #18 - Mutations
GraphQL Tutorial #18 - Mutations
Net Ninja
22 GraphQL Tutorial #19 - More on Mutations
GraphQL Tutorial #19 - More on Mutations
Net Ninja
23 GraphQL Tutorial #20 - Updating the Resolve Functions
GraphQL Tutorial #20 - Updating the Resolve Functions
Net Ninja
24 GraphQL Tutorial #21 - GraphQL NonNull
GraphQL Tutorial #21 - GraphQL NonNull
Net Ninja
25 GraphQL Tutorial #22 - Adding a Front-end
GraphQL Tutorial #22 - Adding a Front-end
Net Ninja
26 GraphQL Tutorial #23 - Create React App
GraphQL Tutorial #23 - Create React App
Net Ninja
27 GraphQL Tutorial #24 - Book List Component
GraphQL Tutorial #24 - Book List Component
Net Ninja
28 GraphQL Tutorial #25 - Apollo Client Setup
GraphQL Tutorial #25 - Apollo Client Setup
Net Ninja
29 GraphQL Tutorial #26 - Making Queries from React
GraphQL Tutorial #26 - Making Queries from React
Net Ninja
30 GraphQL Tutorial #27 - Rendering Data in a Component
GraphQL Tutorial #27 - Rendering Data in a Component
Net Ninja
31 GraphQL Tutorial #28 - Add Book Component
GraphQL Tutorial #28 - Add Book Component
Net Ninja
32 GraphQL Tutorial #29 - External Query File
GraphQL Tutorial #29 - External Query File
Net Ninja
33 GraphQL Tutorial #30 - Updating Component State
GraphQL Tutorial #30 - Updating Component State
Net Ninja
34 GraphQL Tutorial #31 - Composing Queries
GraphQL Tutorial #31 - Composing Queries
Net Ninja
35 GraphQL Tutorial #32 - query variables
GraphQL Tutorial #32 - query variables
Net Ninja
36 GraphQL Tutorial #33 - Re-fetching Queries
GraphQL Tutorial #33 - Re-fetching Queries
Net Ninja
37 GraphQL Tutorial #34 - Book Details Component
GraphQL Tutorial #34 - Book Details Component
Net Ninja
38 GraphQL Tutorial #36 - Styling the App
GraphQL Tutorial #36 - Styling the App
Net Ninja
39 GraphQL Tutorial #35 - Making a Single Query
GraphQL Tutorial #35 - Making a Single Query
Net Ninja
40 Build Apps with Vue & Firebase - Udemy Course
Build Apps with Vue & Firebase - Udemy Course
Net Ninja
41 Updated Vue & Firebase Course (Udemy)
Updated Vue & Firebase Course (Udemy)
Net Ninja
42 Vue & Firebase Real-time Chat (Preview) #1 - Intro
Vue & Firebase Real-time Chat (Preview) #1 - Intro
Net Ninja
43 Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Net Ninja
44 Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Net Ninja
45 Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Net Ninja
46 Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Net Ninja
47 Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Net Ninja
48 Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Net Ninja
49 Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Net Ninja
50 Object Oriented JavaScript Tutorial #1 - Introduction
Object Oriented JavaScript Tutorial #1 - Introduction
Net Ninja
51 Object Oriented JavaScript Tutorial #2 - Object Literals
Object Oriented JavaScript Tutorial #2 - Object Literals
Net Ninja
52 Object Oriented JavaScript Tutorial #3 - Updating Properties
Object Oriented JavaScript Tutorial #3 - Updating Properties
Net Ninja
53 Object Oriented JavaScript Tutorial #4 - Classes
Object Oriented JavaScript Tutorial #4 - Classes
Net Ninja
54 Object Oriented JavaScript Tutorial #5  - Class Constructors
Object Oriented JavaScript Tutorial #5 - Class Constructors
Net Ninja
55 Object Oriented JavaScript Tutorial #6 - Class Methods
Object Oriented JavaScript Tutorial #6 - Class Methods
Net Ninja
56 Object Oriented JavaScript Tutorial #7 - Method Chaining
Object Oriented JavaScript Tutorial #7 - Method Chaining
Net Ninja
57 Object Oriented JavaScript Tutorial #8 - Class Inheritance
Object Oriented JavaScript Tutorial #8 - Class Inheritance
Net Ninja
58 Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Net Ninja
59 Object Oriented JavaScript Tutorial #10 - Prototype
Object Oriented JavaScript Tutorial #10 - Prototype
Net Ninja
60 Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Net Ninja

This video tutorial teaches you how to create a custom React hook for handling user sign-up logic in a MERN application. You'll learn how to create a reusable hook, send POST requests to the server, and update the auth context with user data. By the end of this tutorial, you'll be able to implement authentication and authorization in your own MERN applications.

Key Takeaways
  1. Create a new file called useSignup.js
  2. Import useState and useAuthContext in the hook
  3. Set up state for error and loading in the hook
  4. Create a function called signup to handle the sign-up logic
  5. Use the fetch API to send a POST request to the server
  6. Update the auth context with the user's email if the sign-up is successful
  7. Use local storage to store the user's token
💡 Creating a custom React hook for handling user sign-up logic can help simplify your code and make it more reusable.

Related Reads

📰
Java: Word to TXT Conversion
Learn to convert Word documents to plain text in Java, a crucial task in software development
Dev.to · Jeremy K.
📰
The New HTTP QUERY Method: How to Use It in Node.js and Express Today
Learn to use the new HTTP QUERY method in Node.js and Express to send requests with a body while keeping data safe
Dev.to · Dev Encyclopedia
📰
2 @Transactional Traps That Catch Even Senior Java Developers in interviews
Learn to avoid common @Transactional traps in Java to improve your coding skills and ace technical interviews
Dev.to · Nikhil Kamani
📰
10th Anniversary of the Excelize Open Source, New ersion 2.11.0 Released
Celebrate the 10th anniversary of Excelize, an open-source library for working with XLSX files, and learn how to use its new version 2.11.0 for improved productivity
Dev.to AI
Up next
Indian Express Editorial Analysis by Chandan Sharma - 1 JULY 2026 | UPSC Current Affairs 2026
StudyIQ IAS
Watch →