Eduardo
Eduardo

Reputation: 1831

Firebase currentUser and onAuthStateChanged

I am developing an app using react native, every time I refresh the app on the emulator in onAuthStateChanged and currentUser from firebase I get null.

I have read about waiting onAuthStateChanged to get a status update but I never do, so I guess I misconfigured something.

I am using expo 44, react 17, firebase 9.6.5 but in compat mode (planning in fully migrate later)

My first attempt of solution was trying to add persistence: firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL);

import firebase from "firebase/compat/app";
import "firebase/compat/auth";
import "firebase/compat/firestore";
import "firebase/compat/functions";
import "firebase/compat/storage";
import AsyncStorage from "@react-native-async-storage/async-storage";

import { firebaseConfig } from "./firebase/firebaseConfig";

firebase.initializeApp(firebaseConfig);

firebase.firestore();
firebase.functions();
firebase.storage();
firebase.auth();

firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL);
firebase.auth().onAuthStateChanged(async (user) => {
    console.log("onAuthStateChanged called: ", user);
    if (user) {
        await AsyncStorage.setItem('@isLoggedIn', '1');
    } else {
        await AsyncStorage.setItem('@isLoggedIn', '0');
    }
});

export default firebase;

But I get an error:

undefined is not an object (evaluating 'this.storage.setItem')
at node_modules/@firebase/auth/dist/esm2017/index-cff4f2fd.js:5248:0 in verifyBeforeUpdateEmail
at node_modules/@firebase/auth/dist/esm2017/index-cff4f2fd.js:5420:12 in _fromIdTokenResponse
at http://127.0.0.1:19000/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&minify=false:183132:41 in _set
at node_modules/@firebase/auth/dist/esm2017/index-cff4f2fd.js:1414:55 in newData.some$argument_0
at node_modules/@firebase/auth/dist/esm2017/index-cff4f2fd.js:2060:1 in <global>
at node_modules/@firebase/auth/dist/esm2017/index-cff4f2fd.js:2047:30 in _isIOS
at node_modules/@firebase/auth/dist/esm2017/index-cff4f2fd.js:1890:4 in PersistenceUserManager.create
at node_modules/@firebase/auth/dist/esm2017/index-cff4f2fd.js:1890:4 in PersistenceUserManager.create

to Login I use:

userCredential = firebase
          .auth()
          .signInWithEmailAndPassword(data.email, this.state.password);

Upvotes: 4

Views: 2292

Answers (1)

Dhruv Gairola
Dhruv Gairola

Reputation: 9182

I had this exact same issue. I solved it by adding "firebase": "^8.9.1" to package.json, running yarn install and changing the import import firebase from "firebase" (remove all the other imports you have). Apparently selective imports have a bug in v8, but at least it works well :)

Upvotes: 1

Related Questions