Amplify-js: Current User information for React using React Hooks

Created on 28 Jan 2019  路  7Comments  路  Source: aws-amplify/amplify-js

When using Auth module for React (web), after reading the documentation, I remain a little unclear on how to best leverage the authentication information for a typical React component. Consider the following:

  • Code is being written using TypeScript
  • App is being wrapped with withAuthenticator
  • Components are written as Functions using React Hooks, such as useEffect

Consider the following sample code:

import React, { useState, useEffect } from 'react';
import { Auth } from 'aws-amplify';

const Hello = () => {

  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(true);
  const [username, setUsername] = useState('');

  useEffect(() => {
    try {
      setError(null);
      setLoading(true);

      Auth.currentAuthenticatedUser({
        bypassCache: false  // Optional, By default is false. If set to true, this call will send a request to Cognito to get the latest user data
      }).then(user => {
        setUsername(user.username);
        console.log(`Load additional settings for user: ${user.username}`);
        // TBD
      }).catch(err => setError(err));
    }
    catch (e) {
      setError(e);
    }
    finally {
      setLoading(false);
    }
  }, []);

  return (
    <div>
      {error ? `Oops... ${error}` : null}
      {loading ? "Loading..." : `Hello ${username}`}
    </div>
  )

};

export default Hello;

While the above works, I am left with questions...

  1. Is there a more efficient or direct way to access the _current user_ than to call an _async_ function (Auth.currentAuthenticatedUser())?
  2. Is username the appropriate _key_ to use to reference a user?

    • Imagine I have more metadata to track for a user, such as roles, subscription-end-date, etc. Presumably this would be stored in a table/store somewhere. What should I use as a primary & foreign key?

    • Normally, username is flawed because people can change their names.

  3. Should a component (other than App) specify true for bypassCache to be more efficient? (Since the App tag is likely going to have bypassCache set to false.)
  4. Should authentication information be placed in a Context for components to access? (Should this be something that Amplify does out of the box?)
  5. If the App component is being wrapped with withAuthenticator, then should any other child component really need to be wrapped with withAuthenticator? (No, right?)
Auth investigating pending-close-response-required question

Most helpful comment

Just discovered. I you have autheticated it's possible to get Auth.user which is sync and has all the same details as the async call.

Another observation is if you use email as username, then username and sub values match up.

All 7 comments

  1. What's wrong with async function? you could always use it in the async/await. I don't think there are any other ways.
  2. The user.attributes.sub is unique in Cognito.
  3. Dunno
  4. Auth is a singleton, so you could import it and use it where needed.
  5. Don't think so.

Anyways this are just my thoughts, someone from the team should give you more definite answer.

Just discovered. I you have autheticated it's possible to get Auth.user which is sync and has all the same details as the async call.

Another observation is if you use email as username, then username and sub values match up.

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

This issue has been automatically closed because of inactivity. Please open a new issue if are still encountering problems.

@awhitford As a React Hooks user, you may be interested in sharing your impressions on https://github.com/aws-amplify/amplify-js/issues/4235.

If there's enough interest, Auth is another candidate for simplifying integration within your code via hooks.

Auth.user.username

if you have your app wrapped with "withAuthenticator" then where ever you need the username, email whatever all you need to is set up a function to get the current user.
function getUser() {
let user = Auth.user.username;
return user;
}
console.log( "username is: ", getUser() )

this will give you the username that you can use anywhere in the app. if you just do Auth.user you will get back all of the user information. just replace username with whatever attribute you need from the user.

Was this page helpful?
0 / 5 - 0 ratings