Question:
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
state = { isAuthenticated: false } authenticate(isAuthenticated) { this.setState({ isAuthenticated }) } render() { if (this.state.isAuthenticated) { console.log('Auth: ', Auth) return ( ) } return ( screenProps={{ authenticate: this.authenticate.bind(this) }} /> ); } } |
Answer:
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
... // 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 } else { return } } } |