Created
November 1, 2017 20:55
-
-
Save amackintosh/4d4fd87ddd327188aa06e07403606b52 to your computer and use it in GitHub Desktop.
requireAuth Higher-order Component for React Native
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 { connect } from 'react-redux' | |
import { NavigationActions } from 'react-navigation' | |
export default function (ComposedComponent) { | |
class Authentication extends Component { | |
componentWillMount() { | |
if (!this.props.isAuthenticated) { | |
return this.props.navigation.dispatch(NavigationActions.reset({ | |
index: 0, | |
key: null, | |
actions: [NavigationActions.navigate({ routeName: 'Login' })] | |
})) | |
} | |
} | |
componentWillReceiveProps(nextProps) { | |
if (!nextProps.isAuthenticated) { | |
return this.props.navigation.dispatch(NavigationActions.reset({ | |
index: 0, | |
key: null, | |
actions: [NavigationActions.navigate({ routeName: 'Login' })] | |
})) | |
} | |
} | |
render() { | |
if (!this.props.isAuthenticated) return null | |
return ( | |
<ComposedComponent {...this.props} /> | |
) | |
} | |
} | |
const mapStateToProps = ({ auth: { isAuthenticated } }) => ({ isAuthenticated }) | |
return connect(mapStateToProps, null)(Authentication) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment