How do you persist firebase auth state in react native?

68 Views Asked by At

I'm using React 18.2.0, React Native 0.73.0, Firebase 10.7.1.

signInWithEmailAndPassword(auth, email, password)
      .then(async user => {
        await AsyncStorage.setItem('user', JSON.stringify(user));
        dispatch(login({user: user}));
        navigation.navigate('BottomNavbar');
      })
      .catch(error => {
        console.log(error);
      });
  onAuthStateChanged(auth, async user => {
    if (user) {
      await AsyncStorage.setItem('user', JSON.stringify(user));
      dispatch(login({user: user}));
      navigation.navigate('BottomNavbar');
    }
  });

I'm trying to persist auth state here, I have tried ways like persisting the user data in Async storage and checking whether the data is there whenever the user opens the app and if yes I'm redirecting to home page otherwise to login page. Is it the right way to do?

const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
setPersistence(auth, 'LOCAL');

When I try to use the above code I'm getting an error and a warning like:

@firebase/auth: Auth (10.7.1): INTERNAL ASSERTION FAILED: Expected a class definition

Another question is, I want to make an api request with user's tokenId, how this tokenId is getting updated whenever one gets expired. Or is there some method I have to call/listen to handle this situation?

1

There are 1 best solutions below

4
zackrypaul On

Usually firebase does this out the box, at least for me.

However the most recent app I created, I had to created a "workaround" after removing the "ASYNCStorage has been removed..." error react native would give.

In my firebase file I imported getReactNativePersistence and ASYNC storage.

import { getReactNativePersistence } from "firebase/auth/react-native";
import ReactNativeAsyncStorage from "@react-native-async-storage/async-storage";
const app = initializeApp(firebaseConfig);
// After initializing the app, I use local storage to persist the auth state.

const lStorage = getReactNativePersistence(ReactNativeAsyncStorage);

// pass this storage into the auth variable when you initialize the auth
export const auth = initializeAuth(app, {
  persistence: lStorage,
});

After this change, my auth state is properly persisted.