Last active
September 1, 2024 15:15
-
-
Save onedebos/bbf7cd4634bce53103c1cfefa6164637 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
setUser(foundUser); | |
} | |
}, []); | |
// logout the user | |
const handleLogout = () => { | |
setUser({}); | |
setUsername(""); | |
setPassword(""); | |
localStorage.clear(); | |
}; | |
// login the user | |
const handleSubmit = async e => { | |
e.preventDefault(); | |
const user = { username, password }; | |
// send the username and password to the server | |
const response = await axios.post( | |
"http://blogservice.herokuapp.com/api/login", | |
user | |
); | |
// set the state of the user | |
setUser(response.data); | |
// store the user in localStorage | |
localStorage.setItem("user", JSON.stringify(response.data)); | |
}; | |
// if there's a user show the message below | |
if (user) { | |
return ( | |
<div> | |
{user.name} is loggged in | |
<button onClick={handleLogout}>logout</button> | |
</div> | |
); | |
} | |
// if there's no user, show the login form | |
return ( | |
<div> | |
<form onSubmit={handleSubmit}> | |
<label htmlFor="username">Username: </label> | |
<input | |
type="text" | |
value={username} | |
placeholder="enter a username" | |
onChange={({ target }) => setUsername(target.value)} | |
/> | |
<div> | |
<label htmlFor="password">password: </label> | |
<input | |
type="password" | |
value={password} | |
placeholder="enter a password" | |
onChange={({ target }) => setPassword(target.value)} | |
/> | |
</div> | |
<button type="submit">Login</button> | |
</form> | |
</div> | |
); | |
}; | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.