I have already done getting the user from aws cognito and how can I do it properly to keep the user logged in even when the react native app is closed
state = {
isAuthenticated: false
}
authenticate(isAuthenticated) {
this.setState({ isAuthenticated })
}
render() {
if (this.state.isAuthenticated) {
console.log('Auth: ', Auth)
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Hello {Auth.user.username}!</Text>
</View>
)
}
return (
<View style={styles.container}>
<Tabs
screenProps={{
authenticate: this.authenticate.bind(this)
}}
/>
</View>
);
}
}
If you're using the Auth API provided from Amplify, once you use Auth.signIn, that API will manage your session state.
In your main entry component (probably App.js) check in the componentDidMount() method what Auth.currentAuthenticatedUser() will return before and after you've signed in with a valid user.
... // standard imports
import Amplify, { Auth } from 'aws-amplify';
import awsmobile from './aws-exports';
Amplify.configure(awsmobile);
class App extends Component {
state = { isLoggedIn: false }
...
async componentDidMount() {
try {
const authedUser = await Auth.currentAuthenticatedUser();
console.log(authedUser) // this means that you've logged in before with valid user/pass.
this.setState({ isLoggedIn: true })
} catch(err) {
console.log(err) // this means there is no currently authenticated user
}
}
render() {
if(this.state.isLoggedIn) {
return <Homescreen /> // or whatever your entry component is
}
else {
return <Login />
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With