最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I set Auth State Persistance using firebasecompatauth? - Stack Overflow

programmeradmin0浏览0评论

I am using Expo for my React native project. Every time I close the app the user is signed off and I tried every possible answer on stack overflow to persist the user state. Obviously I am doing something wrong, but the documents on firebase state persistance use firebase/auth while in my config file I am using firebase/compat/auth. Here is my config file:

import firebase from "firebase/compat/app";
import 'firebase/compat/firestore'
import 'firebase/compat/auth'

import { getReactNativePersistence, setPersistence } from 'firebase/auth';
import ReactNativeAsyncStorage from '@react-native-async-storage/async-storage';

const localPersistence = getReactNativePersistence(ReactNativeAsyncStorage);

const firebaseConfig = {
  apiKey: "key",
  authDomain: "domain",
  databaseURL: "url",
  projectId: "id",
  storageBucket: "bucket",
  messagingSenderId: "id",
  appId: "id",
  measurementId: "id"
};

if (firebase.apps.length === 0) {
  firebase.initializeApp(firebaseConfig);
}

export const auth = firebase.auth();
export const firestore = firebase.firestore();

And then in my SignIn.js component I am importing auth from the above file:

import { auth } from '../../firebase.js'

export default function SignIn({ navigation }) {

  const [email, setEmail] = useState(null);
  const [password, setPassword] = useState(null);



  const onLogin = async () => {
    if(!email || !password){
      return;
    }
    auth.signInWithEmailAndPassword(email, password)
      .then((userCredential) => {
        const user = userCredential.user;
      })
      .catch((error) => {
        const errorCode = error.code;
        const errorMessage = error.message;
        console.log("error while user logs in: ", error);
        if(errorCode === "auth/invalid-credential"){
          setError("The supplied auth credential is incorrect, malformed or has expired.")
        }else{
          setError("An error occured and we can not log you in.")
        }
      });
  };

  return (
     <MyComponent />
  );
}

I tried calling

const authState = firebase.auth();
authState.setPersistence(localPersistence);
export const auth = authState;

from my firebase config file, it did not make any difference - the user was always logged out.

I also tried calling setPersistence from my SignIn.js file but then I could not log in (I think the problem was that I was mixing firebase/compat/auth with firebase/auth)

As I said the documentation is using firebase/auth while I am using firebase/compat/auth. Can someone please advice? Keeping user logged in the app is very important for me.

EDIT

Since onAuthStateChanged was mentioned, I wanted to put part of my App.js file:

import { auth } from './firebase.js'

import MainNavigator from "./components/navigation/MainNavigator";

import AuthNavigator from "./components/auth/AuthNavigator";

import { Provider } from "react-redux";

const App = () => {

  const [logged, setLogged] = useState(false);


  useEffect(() => {
   const unsubscribe = auth.onAuthStateChanged((user) =>  {
        console.log("calling onAuthStateChanged listener: ", user)
        if (user) {
          setLogged(true);
        }else{
          setLogged(false);
        }
    });
   return () => unsubscribe();
}, []);


  if(!logged){
      return (
        <NavigationContainer>
          <AuthNavigator />
        </NavigationContainer>
      );
  }
  else{
    return (
      <Provider store={store}>
        <NavigationContainer>
          <MainNavigator />
        </NavigationContainer>
      </Provider>
    );
  }
};

export default App;

I am using Expo for my React native project. Every time I close the app the user is signed off and I tried every possible answer on stack overflow to persist the user state. Obviously I am doing something wrong, but the documents on firebase state persistance use firebase/auth while in my config file I am using firebase/compat/auth. Here is my config file:

import firebase from "firebase/compat/app";
import 'firebase/compat/firestore'
import 'firebase/compat/auth'

import { getReactNativePersistence, setPersistence } from 'firebase/auth';
import ReactNativeAsyncStorage from '@react-native-async-storage/async-storage';

const localPersistence = getReactNativePersistence(ReactNativeAsyncStorage);

const firebaseConfig = {
  apiKey: "key",
  authDomain: "domain",
  databaseURL: "url",
  projectId: "id",
  storageBucket: "bucket",
  messagingSenderId: "id",
  appId: "id",
  measurementId: "id"
};

if (firebase.apps.length === 0) {
  firebase.initializeApp(firebaseConfig);
}

export const auth = firebase.auth();
export const firestore = firebase.firestore();

And then in my SignIn.js component I am importing auth from the above file:

import { auth } from '../../firebase.js'

export default function SignIn({ navigation }) {

  const [email, setEmail] = useState(null);
  const [password, setPassword] = useState(null);



  const onLogin = async () => {
    if(!email || !password){
      return;
    }
    auth.signInWithEmailAndPassword(email, password)
      .then((userCredential) => {
        const user = userCredential.user;
      })
      .catch((error) => {
        const errorCode = error.code;
        const errorMessage = error.message;
        console.log("error while user logs in: ", error);
        if(errorCode === "auth/invalid-credential"){
          setError("The supplied auth credential is incorrect, malformed or has expired.")
        }else{
          setError("An error occured and we can not log you in.")
        }
      });
  };

  return (
     <MyComponent />
  );
}

I tried calling

const authState = firebase.auth();
authState.setPersistence(localPersistence);
export const auth = authState;

from my firebase config file, it did not make any difference - the user was always logged out.

I also tried calling setPersistence from my SignIn.js file but then I could not log in (I think the problem was that I was mixing firebase/compat/auth with firebase/auth)

As I said the documentation is using firebase/auth while I am using firebase/compat/auth. Can someone please advice? Keeping user logged in the app is very important for me.

EDIT

Since onAuthStateChanged was mentioned, I wanted to put part of my App.js file:

import { auth } from './firebase.js'

import MainNavigator from "./components/navigation/MainNavigator";

import AuthNavigator from "./components/auth/AuthNavigator";

import { Provider } from "react-redux";

const App = () => {

  const [logged, setLogged] = useState(false);


  useEffect(() => {
   const unsubscribe = auth.onAuthStateChanged((user) =>  {
        console.log("calling onAuthStateChanged listener: ", user)
        if (user) {
          setLogged(true);
        }else{
          setLogged(false);
        }
    });
   return () => unsubscribe();
}, []);


  if(!logged){
      return (
        <NavigationContainer>
          <AuthNavigator />
        </NavigationContainer>
      );
  }
  else{
    return (
      <Provider store={store}>
        <NavigationContainer>
          <MainNavigator />
        </NavigationContainer>
      </Provider>
    );
  }
};

export default App;
Share Improve this question edited Feb 1 at 20:40 newbie coder asked Feb 1 at 19:47 newbie codernewbie coder 8381 gold badge12 silver badges30 bronze badges 2
  • 2 This is a very common mistake, and it's almost never a matter of persistence settings (persistence is enabled by default). Users are always signed out when your page first loads, and you're supposed to use onAuthStateChanged to find out when the user is known, since it takes a round trip with Firebase to validate their persisted token. This is illustrated in the documentation. Your app code should defer doing anything that requires auth until that observer is invoked with a user object. – Doug Stevenson Commented Feb 1 at 20:30
  • @DougStevenson Thanks for your comment, however I am using onAuthStateChanged in my App.js file. I updated my question, included the App.js file. Any other suggestions where my mistake could be? – newbie coder Commented Feb 1 at 20:41
Add a comment  | 

1 Answer 1

Reset to default -1

I use redux-persist for auth state persistence in AsyncStorage. I hope this is what you need.

https://github/rt2zz/redux-persist#readme

发布评论

评论列表(0)

  1. 暂无评论