|
| 1 | +import { |
| 2 | + createContext, |
| 3 | + ReactNode, |
| 4 | + useCallback, |
| 5 | + useContext, |
| 6 | + useMemo, |
| 7 | + useState, |
| 8 | +} from "react"; |
| 9 | +import { |
| 10 | + createUserWithEmailAndPassword, |
| 11 | + signInWithEmailAndPassword, |
| 12 | + signOut, |
| 13 | + User, |
| 14 | +} from "firebase/auth"; |
| 15 | +import { auth } from "../firebase/firebase"; |
| 16 | +import { useLocalStorage } from "./useLocalStorage"; |
| 17 | +import { useNavigate } from "react-router-dom"; |
| 18 | + |
| 19 | +interface AuthContextData { |
| 20 | + user: User | undefined; |
| 21 | + error: string; |
| 22 | + signUp: (email: string, password: string) => void; |
| 23 | + login: (email: string, password: string) => void; |
| 24 | + logout: () => void; |
| 25 | +} |
| 26 | + |
| 27 | +interface AuthContextProviderProps { |
| 28 | + children: ReactNode; |
| 29 | +} |
| 30 | + |
| 31 | +const AuthContext = createContext<AuthContextData>({ |
| 32 | + user: undefined, |
| 33 | + error: "", |
| 34 | + signUp: (email: string, password: string) => undefined, |
| 35 | + login: (email: string, password: string) => undefined, |
| 36 | + logout: () => undefined, |
| 37 | +}); |
| 38 | + |
| 39 | +export function AuthContextProvider({ children }: AuthContextProviderProps) { |
| 40 | + const navigate = useNavigate(); |
| 41 | + const [user, setUser] = useLocalStorage("user", undefined); |
| 42 | + const [error, setError] = useState<string>(""); |
| 43 | + |
| 44 | + const signUp = useCallback( |
| 45 | + (email: string, password: string) => { |
| 46 | + createUserWithEmailAndPassword(auth, email, password) |
| 47 | + .then((u) => setUser(u.user)) |
| 48 | + .catch((e) => setError(e.message)); |
| 49 | + }, |
| 50 | + [setUser] |
| 51 | + ); |
| 52 | + |
| 53 | + const login = useCallback( |
| 54 | + (email: string, password: string) => { |
| 55 | + signInWithEmailAndPassword(auth, email, password) |
| 56 | + .then((u) => { |
| 57 | + setUser(u.user); |
| 58 | + navigate("/"); |
| 59 | + }) |
| 60 | + .catch((e) => setError(e.message)); |
| 61 | + }, |
| 62 | + [setUser, navigate] |
| 63 | + ); |
| 64 | + |
| 65 | + const logout = useCallback(() => { |
| 66 | + signOut(auth) |
| 67 | + .then(() => setUser(undefined)) |
| 68 | + .catch((e) => setError(e.message)); |
| 69 | + }, [setUser]); |
| 70 | + |
| 71 | + const authContextProviderValue = useMemo( |
| 72 | + () => ({ user, error, signUp, login, logout }), |
| 73 | + [user, error, signUp, login, logout] |
| 74 | + ); |
| 75 | + |
| 76 | + return ( |
| 77 | + <AuthContext.Provider value={authContextProviderValue}> |
| 78 | + {children} |
| 79 | + </AuthContext.Provider> |
| 80 | + ); |
| 81 | +} |
| 82 | + |
| 83 | +export function useAuth() { |
| 84 | + return useContext(AuthContext); |
| 85 | +} |
0 commit comments