I am trying to do backend for my website and I have login, signup, reset password etc. all working. What I am trying to do now is when user log in or sign up, AuthContext to check for file that match his UID and if exist store it to variable or if not exist create it and store it to variable. Just cant get it work. Best i got so far is code at bottom but problem there is when I log out user I am getting all sort errors because user not exists anymore.
my context file look like this so far and everything is working:
import { createContext, useContext, useEffect, useState } from "react";
import { auth, db } from "../firebase";
export const AuthContext = createContext();
export const useAuth = () => {
return useContext(AuthContext);
};
const AuthContextProvider = ({ children }) => {
const [currentUser, setCurrentUser] = useState(null);
const [currentUserDoc, setCurrentUserDoc] = useState(null);
const [loading, setLoading] = useState(true);
const signup = (email, password) => {
return auth.createUserWithEmailAndPassword(email, password);
};
const login = (email, password) => {
return auth.signInWithEmailAndPassword(email, password);
};
const logout = () => {
return auth.signOut();
};
const resetPassword = (email) => {
return auth.sendPasswordResetEmail(email);
};
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged((user) => {
setCurrentUser(user);
setLoading(false);
});
return unsubscribe;
}, []);
const value = { currentUser, currentUserDoc, signup, login, logout, resetPassword };
return <AuthContext.Provider value={value}>{!loading && children}</AuthContext.Provider>;
};
export default AuthContextProvider;
I tryed to change useEffect hook to this but can't get it done right:
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged(async (user) => {
setCurrentUser(user);
const userDoc = db.collection("users").doc(user.uid);
await userDoc.get().then((doc) => {
if (doc.exists) {
setCurrentUserDoc(doc.data());
} else {
doc.set({
email: user.email,
first_name: "",
last_name: "",
country: "",
organization: "",
});
}
});
setLoading(false);
});
return unsubscribe;
}, []);
This is error when there is no user logged in:
Code where I am trying to use it:
import styles from "./Header.module.scss";
import { useAuth } from "../../contexts/AuthContext";
const Header = () => {
const { logout, currentUserDoc } = useAuth();
return (
<header className={styles.header}>
<div></div>
<div className={styles.header__user}>
{currentUserDoc.email}
<button onClick={logout}>Log out</button>
</div>
</header>
);
};
export default Header;
