Last active
September 10, 2020 15:50
-
-
Save wobsoriano/7cdb93c2ee2fd81647ea4b8b2ba0fc21 to your computer and use it in GitHub Desktop.
Firebase Auth Hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React, { useState, useEffect, useContext, createContext } from 'react' | |
| import firebase from './firebase' | |
| const AuthContext = createContext() | |
| export const AuthProvider = ({ children }) => { | |
| const auth = useProvideAuth() | |
| return <AuthContext.Provider value={auth}>{children}</AuthContext.Provider> | |
| } | |
| export const useAuth = () => { | |
| return useContext(AuthContext) | |
| } | |
| function useProvideAuth() { | |
| const [user, setUser] = useState(null) | |
| const [loading, setLoading] = useState(null) | |
| const signinWithEmail = (email, password) => { | |
| setLoading(true) | |
| return firebase | |
| .auth() | |
| .signInWithEmailAndPassword(email, password) | |
| .then((response) => { | |
| setUser(response.user) | |
| setLoading(false) | |
| }) | |
| } | |
| const signOut = () => { | |
| return firebase | |
| .auth() | |
| .signOut() | |
| .then(() => setUser(null)) | |
| } | |
| useEffect(() => { | |
| const unsubscribe = firebase.auth().onAuthStateChanged((user) => { | |
| if (user) { | |
| setUser(user) | |
| } else { | |
| setUser(null) | |
| } | |
| }) | |
| return () => unsubscribe() | |
| }, []) | |
| return { | |
| user, | |
| loading, | |
| signinWithEmail, | |
| signOut | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample usage