021fd941da
From issue #29569 that mention `with-firebase` will error when use `measurementId`. I update firebase in this example and changed code into firebase 9 and that error is disappeared. Closes: https://github.com/vercel/next.js/pull/29570 Fixes: https://github.com/vercel/next.js/issues/29569
43 lines
1.4 KiB
JavaScript
43 lines
1.4 KiB
JavaScript
import { useState, useEffect, createContext, useContext } from 'react'
|
|
import { createFirebaseApp } from '../firebase/clientApp'
|
|
import { getAuth, onAuthStateChanged } from 'firebase/auth'
|
|
|
|
export const UserContext = createContext()
|
|
|
|
export default function UserContextComp({ children }) {
|
|
const [user, setUser] = useState(null)
|
|
const [loadingUser, setLoadingUser] = useState(true) // Helpful, to update the UI accordingly.
|
|
|
|
useEffect(() => {
|
|
// Listen authenticated user
|
|
const app = createFirebaseApp()
|
|
const auth = getAuth(app)
|
|
const unsubscriber = onAuthStateChanged(auth, 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 appropriately.
|
|
} finally {
|
|
setLoadingUser(false)
|
|
}
|
|
})
|
|
|
|
// Unsubscribe auth listener on unmount
|
|
return () => unsubscriber()
|
|
}, [])
|
|
|
|
return (
|
|
<UserContext.Provider value={{ user, setUser, loadingUser }}>
|
|
{children}
|
|
</UserContext.Provider>
|
|
)
|
|
}
|
|
|
|
// Custom hook that shorthands the context!
|
|
export const useUser = () => useContext(UserContext)
|