Skip to content

Instantly share code, notes, and snippets.

@samcorcos
Last active May 14, 2019 17:13
Show Gist options
  • Save samcorcos/3a763405e1892243a78e6d4c5f125416 to your computer and use it in GitHub Desktop.
Save samcorcos/3a763405e1892243a78e6d4c5f125416 to your computer and use it in GitHub Desktop.
import React from 'react'
/**
* A component that is used to bind the current user the store using Firebase
*
* @param {function} store.set - must receive a `store` prop that has a `set` function
* @param {Object} firebase - must receive an initialized `firebase` as a prop
*
* Render this alongside the top-level component of your app. Should only be rendered once.
*/
class AuthBindings extends React.Component {
constructor (props) {
super(props)
this.authListener = this.authListener.bind(this)
this.authListener(props.store)
if (!props.firebase) {
throw new Error('Must pass `firebase` as a prop to `AuthBindings`')
}
}
authListener (store) {
this.stateListener = this.props.firebase.auth().onAuthStateChanged((user) => {
if (user) {
store.set('currentUser', user)
} else {
// You can do something here if user is not logged in
}
})
}
componentWillUnmount () {
this.stateListener = undefined
this.authListener = undefined
}
render () {
return null
}
}
export default AuthBindings
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment