Storing Signup and Login details to LocalStorage Using Typescript/React

Table of contents

No heading

No headings in the article.

The LocalStorage is an in-built memory that comes with the respective browsers. Sometimes we want to quickly store data in the LocalStorage and "Get" those data back when we want to use them.

A typical example that I will address in this article is the Signup and Login form and how to get it functional using Typescript/React. Let's get to it!

For the Signup file, we would implore the "useRef" hook from the react library to reference our input form.

import React, { useRef } from "react"

const Signup = () => {
  const name = useRef<HTMLInputElement>(null);
  const email = useRef<HTMLInputElement>(null);
  const password = useRef<HTMLInputElement>(null);

return (
    <div>
        <div>
            <input
                type="text"
                ref={name}
                placeholder="Name"
                name="name"
              />

            <input
                type="email"
                ref={email}
                placeholder="Email"
                name="email" 
              />

            <input
                type="password"
                ref={password}
                placeholder="Password"
                name="password" 
              />

            <button onClick=""> Signup </button>
        </div>   
    </div>
)
}

Now we must write a function for what will occur when we click on the "Signup" button. To make sure that this works thus far, let us write a function that logs the current values we have filled in the input form, to the console. Make sure to employ the Optional Chaining Operator to avoid any typescript error.

import React, { useRef } from "react"

const Signup = () => {
  const name = useRef<HTMLInputElement>(null);
  const email = useRef<HTMLInputElement>(null);
  const password = useRef<HTMLInputElement>(null);

  const handleSignup = () => {
    console.log(name?.current?.value, email?.current?.value,                                                                  password?.current?.value)    
} 

return (
    <div>
        <div>
            <input
                type="text"
                ref={name}
                placeholder="Name"
                name="name"
              />

            <input
                type="email"
                ref={email}
                placeholder="Email"
                name="email" 
              />

            <input
                type="password"
                ref={password}
                placeholder="Password"
                name="password" 
              />

            <button onClick={handleSignup}> Signup </button>
        </div>   
    </div>
)
}

This should display the values we just filled in our signup form in the console when we click the "Signup" button. Now we can afford to stop logging the values to the console and establish the connection with the LocalStorage.

import React, { useRef } from "react"

const Signup = () => {
  const name = useRef<HTMLInputElement>(null);
  const email = useRef<HTMLInputElement>(null);
  const password = useRef<HTMLInputElement>(null);

  const handleSignup = () => {
    if (name?.current?.value && email?.current?.value &&                                                     password?.current?.value) {
    localStorage.setItem("name", name?.current?.value);
    localStorage.setItem("email", email?.current?.value);
    localStorage.setItem("password", password?.current?.value);
    localStorage.setItem("signUp", email?.current?.value);
    alert("account created successfully");
}  
}; 

return (
    <div>
        <div>
            <input
                type="text"
                ref={name}
                placeholder="Name"
                name="name"
              />

            <input
                type="email"
                ref={email}
                placeholder="Email"
                name="email" 
              />

            <input
                type="password"
                ref={password}
                placeholder="Password"
                name="password" 
              />

            <button onClick={handleSignup}> Signup </button>
        </div>   
    </div>
)
}

If we go to the Application tab of chrome's developer tools and under the Storage option, we will see the Local Storage subset that will display the current value of the form we just filled in a Key/Value format. I also added the "alert" function to let us know we have successfully created the account.

We could employ the React "useState and useEffect" hooks to handle the change in state(page) when we successfully "Signup" and the effects respectively.

import React, { useRef } from "react"
import Home from "./Home"

const Signup = () => {
  const [home, setHome] = useState(false)  

  const name = useRef<HTMLInputElement>(null);
  const email = useRef<HTMLInputElement>(null);
  const password = useRef<HTMLInputElement>(null);

  const localSignUp = localStorage.getItem("signUp")

  useEffect(() => {
    if(localSignUp) {
        setHome(true)
}
}, [localsignUp])  

  const handleSignup = () => {
    if (name?.current?.value && email?.current?.value &&                                                     password?.current?.value) {
    localStorage.setItem("name", name?.current?.value);
    localStorage.setItem("email", email?.current?.value);
    localStorage.setItem("password", password?.current?.value);
    localStorage.setItem("signUp", email?.current?.value);
    alert("account created successfully");
    window.location.reload();
}  
}; 

return (
    <div>
    {home ? ( 
        <Home />
    ) : (
        <div>
            <input
                type="text"
                ref={name}
                placeholder="Name"
                name="name"
              />

            <input
                type="email"
                ref={email}
                placeholder="Email"
                name="email" 
              />

            <input
                type="password"
                ref={password}
                placeholder="Password"
                name="password" 
              />

            <button onClick={handleSignup}> Signup </button>
        </div>  
)} 
    </div>
);
} ;

Therefore, upon successful Signup, the page will reload as a result of the "reload" function and then we would be routed to the supposed <Home /> page or whichever page we wish to be routed to instead. This about concludes what we need to establish a connection with the LocalStorage to store our "Signup" details.

Now before we proceed to the "Login" part, let us quickly set up a "Logout" and "Delete" button for the supposed "<Home />" page.

const Home = () => {
const handleLogout = () => {
    localStorage.removeItem("signUp");
    window.location.reload
}

const handleDelete = () => {
    localStorage.clear()
    window.location.reload
}

return (
    <div>
        <h1>Home</h1>

        <button onClick={handleLogout}>Logout</button>
        <button onClick={handleDelete}>Delete Account</button>
    </div>
)
}

So, clicking on the logout button will send us out of the Home page and back to the Signup page. Clicking on the delete button will remove our details permanently from the LocalStorage. That is it for the Home page for now. We shall update the Home page again after we are done with the Login page.

Now for the Login Page, we shall be using the React "useRef, useState and useEffect" hooks, just like we did on the Signup page. The general idea for the Login page is to check if the values of the email and password we have submitted in the Login form match what we have already in the LocalStorage from the Signup page. If this is the case, then we will be able to Login to the Home page; if not, then we will get an alert saying we should put in the correct details.

import React, {useState, useEffect, useRef} from "react"

  const Login = () => {
  const [home, setHome] = useState(false) 

  const email = useRef<HTMLInputElement>(null);
  const password = useRef<HTMLInputElement>(null);

  const localEmail = localStorage.getItem("email");
  const localPassword = localStorage.getItem("password");
  const localLogin = localStorage.getItem("logIn"); 

useEffect(() => {
    if (localLogin) {
      setHome(true);
    }
  }, [localLogin]);

 const handleLogin = () => {
    if (
      email?.current?.value === localEmail &&
      password?.current?.value === localPassword
    ) {
    localStorage.setItem("email", email?.current?.value);
    localStorage.setItem("password", password?.current?.value);
    localStorage.setItem("logIn", email?.current?.value);
    window.location.reload();
    } else {
      alert("Please enter valid details");
    }
  };

return (
    <div>
    {home ? ( 
        <Home />
    ) : (
        <div>
            <input
                type="email"
                ref={email}
                placeholder="Email"
                name="email" 
              />

            <input
                type="password"
                ref={password}
                placeholder="Password"
                name="password" 
              />

            <button onClick={handleLogin}> Signup </button>
        </div>  
)} 
    </div>
);
}

And that is it for our Login page. If we put in the wrong details, we will receive an alert saying "Please enter valid details". If the details match, then we will be able to "Login" successfully.

Now we have to update the Home page; specifically, the "handleLogout" function to account for the ability to "Logout" when successfully Logged In by adding a single line of code.

const Home = () => {
const handleLogout = () => {
    localStorage.removeItem("signUp");
    localStorage.removeItem("logIn")
     window.location.reload
}

const handleDelete = () => {
    localStorage.clear()
    window.location.reload
}

return (
    <div>
        <h1>Home</h1>

        <button onClick={handleLogout}>Logout</button>
        <button onClick={handleDelete}>Delete Account</button>
    </div>
)
}

With this, we will be able to Logout successfully after a successful "Login".

This is the end of the article. I hope you find this piece quite helpful!