Skip to content

Instantly share code, notes, and snippets.

@dabit3
Created August 3, 2018 18:00
Show Gist options
  • Save dabit3/84e97ff51c2b3395765f05b2d7fd9c9b to your computer and use it in GitHub Desktop.
Save dabit3/84e97ff51c2b3395765f05b2d7fd9c9b to your computer and use it in GitHub Desktop.
AWS Amplify - Working with Authentication State & withAuthenticator HOC
import React, {Component} from 'react';
import { StyleSheet, Text, View} from 'react-native';
import { Auth } from 'aws-amplify'
import { withAuthenticator } from 'aws-amplify-react-native'
class App extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>Welcome to React Native!</Text>
</View>
);
}
}
export default class Main extends React.Component {
state = {
authState: 'loading'
}
async componentDidMount() {
console.log('componentDidMount called')
try {
const user = await Auth.currentAuthenticatedUser()
this.setState({ authState: 'authenticated' })
} catch (err) {
this.setState({ authState: 'unauthorized' })
}
}
render() {
const WithSignUp = withAuthenticator(App)
switch (this.state.authState) {
case('loading'):
return <Text style={{padding: 30}}>Loading</Text>
case('authenticated'):
return <App />
case('unauthorized'):
return (
<View style={{padding: 30}}>
<Text>Not Authorized</Text>
<Text>Here is some info about the app!</Text>
<Text onPress={
() => this.setState({ authState: 'prompt sign up' })
}>Click here to sign up</Text>
</View>
)
case('prompt sign up'):
return <WithSignUp />
default:
return null
}
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment