I’m trying to do firebase email/password auth with react and I’m getting an error:
"_firebaseWEBPACK_IMPORTED_MODULE_1.default.onAuthStateChanged is not a function
TypeError: _firebaseWEBPACK_IMPORTED_MODULE_1.default.onAuthStateChanged is not a function"
So I guess there must be something wrong with my AuthContext.js code:
import React, { useContext, useState, useEffect } from "react";
import auth from "../firebase";
const AuthContext = React.createContext();
export function useAuth() {
return useContext(AuthContext);
}
export function AuthProvider({ children }) {
const [currentUser, setCurrentUser] = useState();
const [loading, setLoading] = useState(true);
function signup(email, password) {
return auth.createUserWithEmailAndPassword(email, password);
}
function login(email, password) {
return auth.signInWithEmailAndPassword(email, password);
}
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged((user) => {
setCurrentUser(user);
setLoading(false);
});
return unsubscribe;
}, []);
const value = {
currentUser,
login,
signup,
};
return (
<AuthContext.Provider value={value}>
{!loading && children}
</AuthContext.Provider>
);
}
This may not be enough of code so here’s link to full code:
https://github.com/szymanskimateusz/aurora/tree/master
Tried to find solution myself for 3 hours. Unfortunately not successful đ
2
Answers
You seem to be using Firebase SDK version 10, which defaults to using a modular syntax for its API calls. So in that SDK
onAuthStateChanged
is a top-level function, rather than a method on theauth
service.For more on this, see the code sample in the documentation on getting the current user (be sure to use the Web modular API tab as that’s what you’re using), and the documentation on upgrading from the namespaced API to the modular API.
The problem is with the importation of onAuthStateChanged. Instead of using auth.onAuthStateChanged(), you should import it like this:
This allows you to use onAuthStateChanged as a function directly. You can find more details on how to import it correctly in the Firebase documentation.
By making this change, you’ll be able to use onAuthStateChanged as intended and avoid the error.