Files
vercel__next.js/examples/with-firebase/context/userContext.js
Steven 4466ba436b chore(examples): use default prettier for examples/templates (#60530)
## Description
This PR ensures that the default prettier config is used for examples
and templates.

This config is compatible with `prettier@3` as well (upgrading prettier
is bigger change that can be a future PR).

## Changes
- Updated `.prettierrc.json` in root with `"trailingComma": "es5"` (will
be needed upgrading to prettier@3)
- Added `examples/.prettierrc.json` with default config (this will
change every example)
- Added `packages/create-next-app/templates/.prettierrc.json` with
default config (this will change every template)

## Related

- Fixes #54402
- Closes #54409
2024-01-11 16:01:44 -07:00

44 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);