I am developing an application in React - Express - Mongo, how can i keep the user logged even after the browser is closed or page is refreshed?
CodePudding user response:
A simple example for your understanding ,how to usage of localStorage, sessionStorage.
https://www.geeksforgeeks.org/difference-between-local-storage-session-storage-and-cookies/
// After hitting login button
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', response.data)
console.log(response.data)
};
CodePudding user response:
Assuming you have something like this:
const MyComponent = () => {
const [isLoggedIn, setIsLoggedIn] = useState(false);
// your code
}
you could do something like this:
const initialLoggedInState = localStorage.getItem('isLoggedIn') ?? false;
const MyComponent = () => {
const [isLoggedIn, setIsLoggedIn] = useState(initialLoggedInState === 'true');
useEffect(() => {
localStorage.setItem('isLoggedIn', isLoggedIn);
}, [isLoggedIn]);
// your code
}