Search code examples
typescriptfirebasereact-nativefirebase-authenticationredux-toolkit

Firebase authentication is not persistent even when using onAuthStateChanged


I'm creating an app using react native w/ expo cli and redux toolkit, here is my rtk mutation for login:

export const loginWithEmail = (builder: Builder) =>
  builder.mutation<Payload | unknown | undefined, Params>({
    queryFn: async ({ email, password }) => {
      try {
        const { user } = await signInWithEmailAndPassword(
          auth,
          email,
          password
        );

        return {
          data: {
            uid: user.uid,
            email: user.email,
            emailVerified: user.emailVerified,
          },
        };
      } catch (error) {
        const authError = error as AuthError;
        return {
          error: { ...authError },
        };
      }
    },
  });

after successfully logging in the authentication state does not persist. Whenever I refresh my app, the onAuthStateChanged callback returns the user as null.

  onAuthStateChanged(auth, (user) => {
    console.log("current-user: ", user); // null when I refresh the app

    if (user) {
      dispatch(setUser({ currentUser: user }));
    }
  });

Here is my firebaseConfig:

import {
  FIREBASE_API_KEY,
  FIREBASE_AUTH_DOMAIN,
  FIREBASE_PROJECT_ID,
  FIREBASE_STORAGE_BUCKET,
  FIREBASE_MESSAGING_SENDER_ID,
  FIREBASE_APP_ID,
  FIREBASE_MEASUREMENT_ID,
} from "@env";

const firebaseConfig = {
  apiKey: FIREBASE_API_KEY,
  authDomain: FIREBASE_AUTH_DOMAIN,
  projectId: FIREBASE_PROJECT_ID,
  storageBucket: FIREBASE_STORAGE_BUCKET,
  messagingSenderId: FIREBASE_MESSAGING_SENDER_ID,
  appId: FIREBASE_APP_ID,
  measurementId: FIREBASE_MEASUREMENT_ID,
};

// Initialize Firebase
const app = getApps().length < 1 ? initializeApp(firebaseConfig) : getApp();
const analytics = getAnalytics(app);
const db = getFirestore(app);
const auth = getAuth(app);

As for the packages they are also pretty standard, nothing special: "firebase": "9.15.0", react-native, expo, rtk

Update: Upon checking on the js debugger, after logging in it doesn't create cookies, session storage or even an indexedDB. So I think this is the reason why the user authentication does not persist, any idea on how can I fix this? I'm pretty sure it should at least generate a session or cookie after logging-in in my react native app.


Solution

  • I was able to fix this problem by installing these packages:

    • expo-application
    • @react-native-async-storage/async-storage
    • react-native-screens