Reputation: 33
I am trying to use the onAuthStateChanged trigger to unsubscribe but I keep getting:
Uncaught TypeError: (0 , firebase_util__WEBPACK_IMPORTED_MODULE_0_.getModularInstance)(...).onAuthStateChanged is not a function below is my 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>
);
}
Upvotes: 2
Views: 3660
Reputation: 21
I have faced the same error when I was working on react native app and because of firebase version change they have update some methods.
I have resolved this by below code and firebase verison is ^9.6.11. you do not need to pull onAuthStateChanged
import { getAuth } from "firebase/auth";
export const yourfunc = () => {
const auth = getAuth();
auth.onAuthStateChanged((user) => {
console.log(user)
}
}
Upvotes: 0
Reputation: 439
You are not subscribing to the StateChange correctly , try the following
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.
}, []);
Upvotes: 2