Created
October 2, 2017 08:02
-
-
Save krizzu/8e499b71c3186fc871144645605e31a1 to your computer and use it in GitHub Desktop.
Example of HoC that check if user is authorised
This file contains 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, { Component } from 'react'; | |
import firebase from './firebase' | |
// Child is our Wrapped component | |
export default (Child) => ( | |
class AuthHoC extends Component { | |
state = { | |
isAuthenticated: false | |
} | |
componentDidMount() { | |
// onAuthStateChanged return a function that we'll use to unsubscribe our listener | |
this.unsubscribeMethod = firebase.auth().onAuthStateChanged(this._handleStateChange); | |
} | |
// is user is null, we're no longer authenticated | |
_handleStateChange = (user) => { | |
this.setState({ | |
isAuthenticated: !!user | |
}) | |
} | |
componentWillUnmount() { | |
if(this.unsubscribeMethod) { | |
this.unsubscribeMethod() | |
} | |
} | |
render() { | |
return <Child isAuthenticated={this.state.isAuthenticated} {...this.props} /> | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment