I have a simple login with firebase, but after a refresh it loses the user. The user gets stored in LocalStorage but on refresh it deletes it from there as well.
const loginform = document.querySelector('.loginform');
const email = loginform.email.value;
const password = loginform.password.value;
signInWithEmailAndPassword(auth, email, password)
.then(cred => {
console.log('user logged in:', cred.user)
loginform.reset()
setPersistence(auth, browserLocalPersistence);
})
const auth = getAuth();
const user = auth.currentUser;
onAuthStateChanged(auth, () => {
const userplace = document.querySelector('.user')
if(userplace != null){
if(user){
userplace.innerHTML = `Welcome, ${user.displayName || user.email}`
}else {
userplace.innerHTML = `Log in`
}
}
})
and of course since there is no user it will show the "log in" text
Firebase automatically persists and restores the user credentials on reloading the app/page.
But your code only handles the situation where the user explicitly signs in. To also handle the restore, have a look at the first code snippet in the documentation on getting the current user:
import { getAuth, onAuthStateChanged } from "firebase/auth";
const auth = getAuth();
onAuthStateChanged(auth, (user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
const uid = user.uid;
// ...
} else {
// User is signed out
// ...
}
});