Skip to content

Instantly share code, notes, and snippets.

@krizzu
Created October 2, 2017 08:02
Show Gist options
  • Save krizzu/8e499b71c3186fc871144645605e31a1 to your computer and use it in GitHub Desktop.
Save krizzu/8e499b71c3186fc871144645605e31a1 to your computer and use it in GitHub Desktop.
Example of HoC that check if user is authorised
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