forked from vercel/next.js
/
userContext.js
40 lines (34 loc) · 1.28 KB
/
userContext.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import { useState, useEffect, createContext, useContext } from 'react'
import firebase from '../firebase/clientApp'
export const UserContext = createContext()
export default ({ children }) => {
const [user, setUser] = useState(null)
const [loadingUser, setLoadingUser] = useState(true) // Helpful, to update the UI accordingly.
useEffect(() => {
// Listen authenticated user
const unsubscriber = firebase.auth().onAuthStateChanged(async user => {
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) {
// Most probably a connection error. Handle appropiately.
} finally {
setLoadingUser(false)
}
})
// Unsubscribe auth listener on unmount
return () => unsubscriber()
}, [])
return (
<UserContext.Provider value={{ user, setUser, loadingUser }}>
{children}
</UserContext.Provider>
)
}
// Custom hook that shorhands the context!
export const useUser = () => useContext(UserContext)