How to Create the Hooks Context ?
first you must create hooks Folder and create AuthContext.js
import { createContext } from "react";
const AuthContext = createContext();
export default AuthContext;
import { createUserWithEmailAndPassword, getAuth, onAuthStateChanged, signInWithEmailAndPassword } from "firebase/auth";
import { useState, useEffect } from 'react';
import { auth, db } from "../Configs/firebase";
import AuthContext from "./hooks/AuthContext";
export const AuthProvider = ({ children }) => {
const [currentUser, setCurrentUser] = useState()
const [subscriptionUser, setSubscriptionUser] = useState()
const [role, setRole] = useState("")
const [loading, setLoading] = useState(true)
const navigate = useNavigate()
const toast = useToast()
const login = (email, password) => {
return signInWithEmailAndPassword(auth, email, password)
}
const signOut = () => {
return auth.signOut()
;
}
const signUp = (email, password) => {
return createUserWithEmailAndPassword(auth, email, password)
}
const getUser = () => {
return auth.currentUser
}
const CustomHooks () => { //you can create your custom hook in here
}
useEffect(() => {
onAuthStateChanged(auth,(user) => {
setCurrentUser(user)
setLoading(false)
})
}, []);
const value = {
currentUser,
getUser,
login,
signOut,
signUp,
}
return (
<AuthContext.Provider value={value}>
{ !loading && children }
</AuthContext.Provider>
);
}
how to call the hooks Context ?
const { currentUser, signOut } = useContext(AuthContext)
console.log(currentUser.email)
const handleLogOut = () => {
signOut()
.then(() => {
navigate("/", { replace: true });
})
.catch((error) => {
console.log(error)
});
};