I am trying to use Context API for user authentication to Firebase from my React app. I wrote the code for the context provider in AuthContext.js which includes all the auth functions. It successfully runs and also provides all the currentuser info.
AuthContext.js
const userAuthContext = createContext();
export function UserAuthContextProvider({ children }) {
const [user, setUser] = useState({});
function logIn(email, password) {
return signInWithEmailAndPassword(auth, email, password);
}
function signUp(email, password) {
return createUserWithEmailAndPassword(auth, email, password);
}
function logOut() {
return signOut(auth);
}
function googleSignIn() {
const googleAuthProvider = new GoogleAuthProvider();
return signInWithPopup(auth, googleAuthProvider);
}
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (currentuser) => {
console.log("Auth", currentuser);
setUser(currentuser);
});
return () => {
unsubscribe();
};
}, []);
return (
<userAuthContext.Provider
value={{ user, logIn, signUp, logOut, googleSignIn }}
>
{children}
</userAuthContext.Provider>
);
}
export function useUserAuth() {
return useContext(userAuthContext);
}
I have also wrapped the App component in UserAuthContextProvider. But when I try to use it in other components like Homepage, it returns an empty object for user. I did a lot of research finding the solution but couldn't really find where the problem lies.
App.js
const App = () => {
return (
<UserAuthContextProvider>
<div className="app">
<div className="navbar">
<Navbar />
</div>
<div className="main">
<Layout>
<div className="header">
<Title level={2} style={{ margin: "0px" }}>
Welcome
</Title>
<Text style={{ margin: "0px", color: "grey" }}>
Here's what's happening in the crypto world
</Text>
</div>
<div
className="
routes"
>
<Routes>
<Route exact path="/" element={<Homepage />} />
<Route exact path="/exchanges" element={<Exchanges />} />
<Route
exact
path="/cryptocurrencies"
element={<Cryptocurrencies />}
/>
<Route
exact
path="/crypto/:coinId"
element={<CryptoDetails />}
/>
<Route exact path="/news" element={<News />} />
<Route exact path="/watchlist" element={<Watchlist />} />
</Routes>
</div>
</Layout>
<div className="footer">
<Typography.Title
level={5}
style={{ color: "white", textAlign: "center" }}
>
Cryptocon <br />© All rights reserved
</Typography.Title>
<Space split={<Divider type="vertical" />}>
<Link to="/">Home</Link>
<Link to="/exchanges">Exchanges</Link>
<Link to="/news">News</Link>
</Space>
</div>
</div>
</div>
</UserAuthContextProvider>
);
};
export default App;
Homepage.jsx
const { user } = useUserAuth();
const { data, isFetching } = useGetCryptosQuery(10);
const globalStats = data?.data?.stats;
if (isFetching) return <Loader />;
-> console.log("The user is: " + user);
return (
<>
...
</>
);
};