Skip to content

Instantly share code, notes, and snippets.

Last active May 30, 2024 13:57
Show Gist options
  • Save onedebos/bbf7cd4634bce53103c1cfefa6164637 to your computer and use it in GitHub Desktop.
Save onedebos/bbf7cd4634bce53103c1cfefa6164637 to your computer and use it in GitHub Desktop.
import React, { useState, useEffect } from "react";
import axios from "axios";
const App = () => {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [user, setUser] = useState();
useEffect(() => {
const loggedInUser = localStorage.getItem("user");
if (loggedInUser) {
const foundUser = JSON.parse(loggedInUser);
}, []);
// logout the user
const handleLogout = () => {
// login the user
const handleSubmit = async e => {
const user = { username, password };
// send the username and password to the server
const response = await
// set the state of the user
// store the user in localStorage
localStorage.setItem("user", JSON.stringify(;
// if there's a user show the message below
if (user) {
return (
{} is loggged in
<button onClick={handleLogout}>logout</button>
// if there's no user, show the login form
return (
<form onSubmit={handleSubmit}>
<label htmlFor="username">Username: </label>
placeholder="enter a username"
onChange={({ target }) => setUsername(target.value)}
<label htmlFor="password">password: </label>
placeholder="enter a password"
onChange={({ target }) => setPassword(target.value)}
<button type="submit">Login</button>
export default App;
Copy link

Web0143 commented May 26, 2022

also give code of backend

Copy link

I searched the whole internet but ain't gain a thing! this is really precious. thank you.

Copy link

You need to secure this as the browser is open to anything. Implement another check on the server if the token is still legit and clear localstorage on logout.

Copy link

Thanks a lot!

Copy link

quyhoaphantruong commented Mar 5, 2023

Storing the entire user information instead of just a token is really dangerous because the user information can be easily hacked. Additionally, it doesn't make sense to use JSON Web Tokens (jsonwebtoken) if you are not using them on the client-side as well. This tutorial is useless.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment