usefirebase
unknown
plain_text
4 years ago
2.8 kB
6
Indexable
import { useState, useEffect } from "react"; import { getAuth, signInWithPopup, GoogleAuthProvider, onAuthStateChanged, signOut, createUserWithEmailAndPassword, signInWithEmailAndPassword, updateProfile, } from "firebase/auth"; import initializeAuthentication from "../Firebase/firebase.init"; initializeAuthentication(); const useFirebase = () => { const [user, setUser] = useState({}); const [loading, setLoading] = useState(true); const [name, setName] = useState(""); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [error, setError] = useState(""); const auth = getAuth(); const googleProvider = new GoogleAuthProvider(); const signInUsingGoogle = () => { return signInWithPopup(auth, googleProvider).finally(() => { setLoading(false); }); }; const logOut = () => { setLoading(true); signOut(auth) .then(() => { setUser({}); }) .finally(() => setLoading(false)); }; // observe whether user auth state changed or not useEffect(() => { const unsubscribe = onAuthStateChanged(auth, (user) => { if (user) { setUser(user); } else { setUser({}); } setLoading(false); }); return () => unsubscribe; }, []); // set username const setUserName = () => { updateProfile(auth.currentUser, { displayName: name, }) .then(() => { // Profile updated! // ... }) .catch((error) => { // An error occurred // ... }); }; // registration const registerNewUser = (email, password) => { createUserWithEmailAndPassword(auth, email, password) .then((result) => { const user = result.user; console.log(user); setError(""); setUserName(); }) .catch((error) => { setError(error.message); }); }; // email login const processLogin = (email, password) => { signInWithEmailAndPassword(auth, email, password) .then((result) => { const user = result.user; console.log(user); setError(""); }) .catch((error) => { setError(error.message); }); }; const handleEmail = (e) => { setEmail(e.target.value); }; const handlePass = (e) => { setPassword(e.target.value); }; const handleNameChange = (e) => { setName(e.target.value); }; return { user, loading, signInUsingGoogle, logOut, handleEmail, handlePass, registerNewUser, handleNameChange, processLogin, email, password, error, }; }; export default useFirebase;
Editor is loading...