Created
May 11, 2020 15:54
-
-
Save polRk/49d73e0b8368ed84c62795520e325a34 to your computer and use it in GitHub Desktop.
React Firebase useAuth
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as firebase from 'firebase/app' | |
import { useEffect, useState, createContext } from 'react' | |
export type AuthState = { | |
initializing: boolean | |
user: firebase.User | null | |
} | |
export const userContext = createContext<AuthState>({ | |
initializing: true, | |
user: null, | |
}) | |
export const useAuth = () => { | |
const [state, setState] = useState<AuthState>({ | |
initializing: true, | |
user: null, | |
}) | |
useEffect(() => { | |
const unsubscribe = firebase.auth().onIdTokenChanged(async (user) => { | |
if (user) { | |
const token = await user.getIdToken() | |
localStorage.setItem('token', token) | |
} | |
}) | |
return () => unsubscribe() | |
}, []) | |
useEffect(() => { | |
const unsubscribe = firebase.auth().onAuthStateChanged(async (user) => { | |
if (user) { | |
const token = await user.getIdToken() | |
localStorage.setItem('token', token) | |
} | |
setState({ initializing: false, user }) | |
}) | |
return () => unsubscribe() | |
}, []) | |
return state | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment