rsnext/examples/with-firebase-authentication-serverless/utils/auth/hooks.js
Kevin Jennison 34f1aefa4a Add example: with-firebase-authentication-serverless (#10078)
* Start from existing example

* Upgrade some dependencies

* Use dotenv

* Remove custom server

* Add serverless Firebase auth

* Add TODOs

* Update project name

* Fix build script

* Remove server middleware from client JS bundle

* Add logout functionality

* Redirect to auth page on logout

* Remove TODO

* Add comments about the cookie-session approach

* Remove the sessions folder

* Add comments for eslint

* Remove unused files

* Clarify comment

* Update README.md

* Rename variable for clarity

* Update README.md

* Change some comments

* Add more to gitignore

* Remove the bundle analyzer

* Move server-side auth user logic from _app.js to a HOC to support static HTML rendering

Co-authored-by: Joe Haddad <timer150@gmail.com>
2020-01-20 16:12:48 -05:00

45 lines
1.1 KiB
JavaScript

import React, { useEffect, useState } from 'react'
import firebase from 'firebase/app'
import 'firebase/auth'
import initFirebase from './initFirebase'
import { setSession } from './firebaseSessionHandler'
import { createAuthUserInfo } from './user'
initFirebase()
// https://benmcmahen.com/using-firebase-with-react-hooks/
// Defaults to empty AuthUserInfo object.
export const AuthUserInfoContext = React.createContext(createAuthUserInfo())
export const useAuthUserInfo = () => {
return React.useContext(AuthUserInfoContext)
}
// Returns a Firebase JS SDK user object.
export const useFirebaseAuth = () => {
const [state, setState] = useState(() => {
const user = firebase.auth().currentUser
return {
initializing: !user,
user,
}
})
function onChange(user) {
setState({ initializing: false, user })
// Call server to update session.
setSession(user)
}
useEffect(() => {
// Listen for auth state changes.
const unsubscribe = firebase.auth().onAuthStateChanged(onChange)
// Unsubscribe to the listener when unmounting.
return () => unsubscribe()
}, [])
return state
}