Search code examples
react-nativeauthenticationaws-amplify

AWS amplify remember logged in user in React Native app


I just started exploring AWS amplify as a backend for my react native application. Being a true beginner on using the service, I want my app to remember the logged in user every time I refresh the emulator.

I know from AWS amplify documentation that I can use the Auth function currentAuthenticatedUser for this purpose, but I have no idea on how to implement a code that does this purpose.

My app looks like this:

App.js

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import AuthTabs from './components/AuthTabs';
import NavigationTab from './components/NavigationTab';

import Amplify, { Auth } from 'aws-amplify';
import AWSConfig from './aws-exports';

Amplify.configure(AWSConfig);

export default class App extends React.Component {
   state = {
   isAuthenticated: false
}

authenticate(isAuthenticated) {
   this.setState({ isAuthenticated })
}

render() {
  if (this.state.isAuthenticated) {
    console.log('Hello', Auth.user.username)
    return(
      <View style={styles.container}>
        <Text style={styles.textStyle}>
          Hello {Auth.user.username}!
        </Text>
        <NavigationTab
          screenProps={
            {authenticate: this.authenticate.bind(this)}
          }
        />
      </View>
    )
  }
  return (
    <View style={styles.container}>
    <AuthTabs
      screenProps={
        {authenticate: this.authenticate.bind(this)}
      }
    />
    </View>
  )
  }
}

Any help would be much appreciated.


Solution

  • I also have come up with a similar solution. But instead of the constructor, I use the life cycle method componentDidMount() to call a method that I named loadApp().

    import React from 'react'
    import {
      StyleSheet,
      View,
      ActivityIndicator,
    } from 'react-native'
    
    import Auth from '@aws-amplify/auth'
    
    export default class AuthLoadingScreen extends React.Component {
      state = {
        userToken: null
      }
      async componentDidMount () {
        await this.loadApp()
      }
      // Get the logged in users and remember them
      loadApp = async () => {
        await Auth.currentAuthenticatedUser()
        .then(user => {
          this.setState({userToken: user.signInUserSession.accessToken.jwtToken})
        })
        .catch(err => console.log(err))
        this.props.navigation.navigate(this.state.userToken ? 'App' : 'Auth')
      }
      render() {
        return (
          <View style={styles.container}>
            <ActivityIndicator size="large" color="#fff" />
          </View>     
        )
      }
    }
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        backgroundColor: '#aa73b7',
        alignItems: 'center',
        justifyContent: 'center',
      },
    })
    

    loadApp() will try and get the user JWT Token by calling the AWS Amplify currentAuthenticatedUser() method. The obtained token is then stored in the component state.

    I have used React navigation version 2 to navigate the user to either the App screen or the Auth stack screen depending on her status: logged in or not logged in.