【问题标题】:Firebase and React TypeError: firebase.auth(...).onAuthStateChanged is not a functionFirebase 和 React TypeError:firebase.auth(...).onAuthStateChanged 不是函数
【发布时间】:2022-07-23 03:37:39
【问题描述】:

我正在尝试使用 onAuthStateChanged 触发器取消订阅,但我不断收到:

Uncaught TypeError: (0 , firebase_util__WEBPACK_IMPORTED_MODULE_0_.getModularInstance)(...).onAuthStateChanged 不是函数 下面是我的 Authcontext.js

import React ,{useEffect, useState ,useContext} from 'react';
import { auth } from '../api/firebase';
    
const AuthContext = React.createContext();    

export function useAuth() {
    return useContext(AuthContext)
}

export function AuthProvider({ children }) {
    const [currentUser, setCurrentUser] = useState(null);        
    const [loading,setLoading] = useState(true);
    
    function register (email,password) { 
        return auth.createUserWithEmailAndPassword(email,password);
    }
    
    useEffect(() => {
        const unsubscribe = auth.onAuthStateChanged(user => {
            setCurrentUser(user);
        });
        return unsubscribe;
    }, []);
    
    const value = {
        currentUser,
        register,
    }
    
    return (
        <AuthContext.Provider value={value}>
            {children}
         </AuthContext.Provider> 
    );
}

【问题讨论】:

  • 你能分享你的 package.json 和你初始化 Firebase 的文件吗?

标签: javascript reactjs firebase firebase-authentication


【解决方案1】:

您没有正确订阅 StateChange,请尝试以下操作

React.useEffect(() => {
    const unsubscribe = firebase.auth().onAuthStateChanged((user) => { // detaching the listener
        if (user) {
            // ...your code to handle authenticated users. 
        } else {
            // No user is signed in...code to handle unauthenticated users. 
        }
    });
    return () => unsubscribe(); // unsubscribing from the listener when the component is unmounting. 
}, []);

【讨论】:

    【解决方案2】:

    我在处理本机应用程序时遇到了同样的错误,并且由于 firebase 版本更改,他们更新了一些方法。

    我已经通过下面的代码解决了这个问题,firebase 版本是 ^9.6.11。 你不需要拉 onAuthStateChanged

    import { getAuth } from "firebase/auth";
    
    export const yourfunc = () => {   
     const auth = getAuth(); 
     auth.onAuthStateChanged((user) => {
     console.log(user)
     } 
    }
    

    【讨论】:

      猜你喜欢
      • 2018-06-22
      • 2019-10-15
      • 2018-08-17
      • 2017-06-23
      • 2018-11-30
      • 2020-09-22
      • 2018-05-30
      • 2021-12-17
      • 2021-11-08
      相关资源
      最近更新 更多