Skip to content

Instantly share code, notes, and snippets.

@wobsoriano
Last active September 10, 2020 15:50
Show Gist options
  • Save wobsoriano/7cdb93c2ee2fd81647ea4b8b2ba0fc21 to your computer and use it in GitHub Desktop.
Save wobsoriano/7cdb93c2ee2fd81647ea4b8b2ba0fc21 to your computer and use it in GitHub Desktop.
Firebase Auth Hook
import React, { useState, useEffect, useContext, createContext } from 'react'
import firebase from './firebase'
const AuthContext = createContext()
export const AuthProvider = ({ children }) => {
const auth = useProvideAuth()
return <AuthContext.Provider value={auth}>{children}</AuthContext.Provider>
}
export const useAuth = () => {
return useContext(AuthContext)
}
function useProvideAuth() {
const [user, setUser] = useState(null)
const [loading, setLoading] = useState(null)
const signinWithEmail = (email, password) => {
setLoading(true)
return firebase
.auth()
.signInWithEmailAndPassword(email, password)
.then((response) => {
setUser(response.user)
setLoading(false)
})
}
const signOut = () => {
return firebase
.auth()
.signOut()
.then(() => setUser(null))
}
useEffect(() => {
const unsubscribe = firebase.auth().onAuthStateChanged((user) => {
if (user) {
setUser(user)
} else {
setUser(null)
}
})
return () => unsubscribe()
}, [])
return {
user,
loading,
signinWithEmail,
signOut
}
}
@wobsoriano
Copy link
Author

wobsoriano commented Sep 10, 2020

Sample usage

// main.js
import { AuthProvider } from './auth'

ReactDOM.render(
    <AuthProvider>
      <App />
    </AuthProvider>,
  document.getElementById('root')
)
// App.js
import { useAuth } from './auth'

function App() {
  const auth = useAuth();

  return (
    <>
      <button onClick={auth.signinWithEmail}>Sign In</button>
      {auth?.user?.email}
      <button onClick={auth.signOut}>Log out</button>
    </>
  )
}

export default App

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment