When I log in or register everything works perfectly. But if I reload the page I have to log in again. Is there any way around this? I have tried setting up persistence myself but it doesn't work. This is my code
const iniciarSesion = (e) => {
const auth = getAuth();
setPersistence(auth, browserLocalPersistence)
.then(() => {
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
setVentana("Tienda")
})
.catch((error) => {
console.log(error)
});
})
}
const registar = (e) => {
const auth = getAuth();
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
setVentana("Tienda")
})
.catch((error) => {
console.error(error)
});
}
In most browser-based environments Firebase already persists and restores the user credentials upon reloading the page. From the Firebase documentation on auth persistence:
For a web application, the default behavior is to persist a user's session even after the user closes the browser. This is convenient as the user is not required to continuously sign-in every time the web page is visited on the same device.
So if your code runs in a browser, you shouldn't need to call setPersistence(auth, browserLocalPersistence). What you do need however, it so detect in your code when Firebase has restored the signed in user.
Restoring the user upon reloading the page requires that Firebase call to the server, to amongst others check if the account has been disabled. While this call is being made, the currentUser will be null. To get notified when the user has been restored, and for other changes in authentication state, you'll want to use an auth state listener as shown in 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
// ...
}
});
In this code you'll then call setVentana("Tienda") to navigate to the correct window.
you can use redux-persist so if reload page , redux store will persist. this document my help you https://react-redux-firebase.com/docs/integrations/redux-persist.html
Implement redux w/ toolkit (easiest way to set up redux IMO) - you can follow this tutorial
Important tip is to update the state with the onAuthStateChanged method available in the firebase package, instead of changing it directly during the sign-in/ sign-up function