Search code examples
reactjsfirebasefirebase-authenticationexponative

Is this Firebase auth state persistent in React Native Expo?


Update: I can login on the web app, close Chrome, reopen the app in Chrome, and I'm still logged in. Seems persistent. Is there another test I should try?

In a react native expo app, I have this error: "You are initializing Firebase Auth for React Native without providing AsyncStorage."

Can the error be ignored or is it valid? I ask because I am using AsyncStorage. To keep my app and auth from reinitializing, they are intialized like this:

const createFirebaseApp = (firebaseConfig = {}) => {
  try {
    return getApp();
  } catch (error) {
    return initializeApp(firebaseConfig);
  }
};

const createAuth = (app) => {
    try {
        return getAuth();
    } catch (error) {
        return initializeAuth(app, {
            persistence: getReactNativePersistence(ReactNativeAsyncStorage)
        });
    }
}

const app = createFirebaseApp(firebaseConfig);
const auth = createAuth(app);

I initially did what the error said and began using AsyncStorage. Then the app and auth were trying to initialize more than once so I put them into try/catch statements. Now it seems Firebase doesn't realize async is being used. Or maybe it is somehow not being used?


Solution

  • It's persistent on web because I can shut down the app and Chrome, rerun npm run web, and I'm still logged in.

    However, if I close Expo on the iPhone and reopen Expo and the app, I'm not still logged in. Is restarting Expo any different from reloading the web page?

    Update: It works on web but not iPhone, so I set it back to this. And I'll just have to ignore the reinitialization warnings while saving files during development.

    Update: Was erroring on web so the code is now:

    import { Platform } from 'react-native';
    
    const createFirebaseApp = (firebaseConfig = {}) => {
      try {
        return getApp();
      } catch (error) {
        return initializeApp(firebaseConfig);
      }
    };
    
    const app = createFirebaseApp(firebaseConfig);
    let auth;
    if (Platform.OS == "web"){
        auth = getAuth();
    }   else {
        auth = initializeAuth(app, {
            persistence: getReactNativePersistence(ReactNativeAsyncStorage)
          });
    }