Skip to content

Instantly share code, notes, and snippets.

@leighhalliday
Created March 2, 2022 13:10
Show Gist options
  • Select an option

  • Save leighhalliday/e5b1b41ba4a23542adbc2fc17439d276 to your computer and use it in GitHub Desktop.

Select an option

Save leighhalliday/e5b1b41ba4a23542adbc2fc17439d276 to your computer and use it in GitHub Desktop.
import {
useEffect,
useState,
useContext,
createContext,
FunctionComponent,
} from "react";
import { firebase } from "./initFirebase";
const AuthContext = createContext({
user: null,
loading: true,
logout: () => {},
});
const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const cancelAuthListener = firebase.auth().onIdTokenChanged((u) => {
setUser(u);
setLoading(false);
});
return () => cancelAuthListener();
}, []);
return (
<AuthContext.Provider
value={{ user, loading, logout: () => firebase.auth().signOut() }}
>
{children}
</AuthContext.Provider>
);
};
function useAuth() {
return useContext(AuthContext);
}
export { AuthProvider, useAuth };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment