Last active
May 14, 2019 17:13
-
-
Save samcorcos/3a763405e1892243a78e6d4c5f125416 to your computer and use it in GitHub Desktop.
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 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