Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep user logged in react-native using aws amplify

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>
    );
  }
}
like image 377
Tommy Avatar asked Nov 08 '22 06:11

Tommy


1 Answers

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 />
     }
   }
}
like image 178
Julian Avatar answered Nov 15 '22 08:11

Julian