简体   繁体   中英

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:

  1. I can login
  2. I can navigate to other pages and my user is persisted
  3. 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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM