userContext.js 1.3 KB
Newer Older
1 2 3 4 5
import { useState, useEffect, createContext, useContext } from 'react'
import firebase from '../firebase/clientApp'

export const UserContext = createContext()

6
export default function UserContextComp({ children }) {
7 8 9 10 11
  const [user, setUser] = useState(null)
  const [loadingUser, setLoadingUser] = useState(true) // Helpful, to update the UI accordingly.

  useEffect(() => {
    // Listen authenticated user
J
Joe Haddad 已提交
12
    const unsubscriber = firebase.auth().onAuthStateChanged(async (user) => {
13 14 15 16 17 18 19 20 21
      try {
        if (user) {
          // User is signed in.
          const { uid, displayName, email, photoURL } = user
          // You could also look for the user doc in your Firestore (if you have one):
          // const userDoc = await firebase.firestore().doc(`users/${uid}`).get()
          setUser({ uid, displayName, email, photoURL })
        } else setUser(null)
      } catch (error) {
N
not 已提交
22
        // Most probably a connection error. Handle appropriately.
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
      } finally {
        setLoadingUser(false)
      }
    })

    // Unsubscribe auth listener on unmount
    return () => unsubscriber()
  }, [])

  return (
    <UserContext.Provider value={{ user, setUser, loadingUser }}>
      {children}
    </UserContext.Provider>
  )
}

T
Tantan Fu 已提交
39
// Custom hook that shorthands the context!
40
export const useUser = () => useContext(UserContext)