'Why is the user not persisted on a page refresh with Firebase and Firebase React Hooks?
I have this setup file:
firebase.ts
import { initializeApp } from 'firebase/app';
import * as firebaseAuth from 'firebase/auth';
import config from './config';
const firebaseApp = initializeApp(config.env.firebase);
export const app = firebaseApp;
export const auth = firebaseAuth.initializeAuth(firebaseApp);
export const signInWithEmailAndPassword = (email: string, password: string) =>
firebaseAuth.signInWithEmailAndPassword(auth, email, password);
export const signOut = () => {
console.log('sign out');
return firebaseAuth.signOut(auth);
};
This is how I'm logging in
login.tsx
// Button onclick...
await signInWithEmailAndPassword(email, password);
history.replace('/');
And on my PrivateRoute component I have
const PrivateRouteComponent: React.FC<Props> = ({ component: Component, ...rest }) => {
const [currentUser, loading, error] = useAuthState(auth);
console.log('[currentUser, loading, error]', [currentUser, loading, error]);
if (loading) {
return null;
}
The actual behavior is:
- I can login
- I can navigate to other pages and my user is persisted
- I refresh the page and the user comes back as
null
The expected is for the user to be persisted if I refresh the page.
Why am I losing the user when I refresh the entire page? Can I keep the user after refreshing the page somehow?
Additional context:
"firebase": "^9.6.7", // migrating from ^7
"react-firebase-hooks": "^5.0.2", // migrating from ^2
Solution 1:[1]
Instead of initializeAuth the correct one to use here is getAuth.
export const auth = firebaseAuth.getAuth(firebaseApp);
By default it seems to persist on IndexDB. You can change it by calling:
firebaseAuth.setPersistence(auth, firebaseAuth.browserLocalPersistence);
firebaseAuth.setPersistence(auth, firebaseAuth.browserSessionPersistence);
firebaseAuth.setPersistence(auth, firebaseAuth.indexedDBLocalPersistence); // default
firebaseAuth.setPersistence(auth, firebaseAuth.inMemoryPersistence);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | BrunoLM |
