question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Current User information for React using React Hooks

See original GitHub issue

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?)

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Reactions:5
  • Comments:8 (1 by maintainers)

github_iconTop GitHub Comments

5reactions
chmelevskijcommented, Feb 13, 2019

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.

2reactions
ericclemmonscommented, Oct 22, 2019

@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.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Hooks API Reference - React
Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class. This page...
Read more >
Manage current user using context and custom hooks in React
In my App component I'm using the useUser custom hook and sharing its methods and properties with the UserContext.Provider. const { currentUser, ...
Read more >
User management met React Hooks - Codious
Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class. If you...
Read more >
useAuth React Hook - useHooks
This is a perfect use-case for a useAuth hook that enables any component to get the current auth state and re-render if it...
Read more >
Using Hooks with React Router - LogRocket Blog
React Hooks were introduced with the release of React v16.8.0 to much excitement. With Hooks, developers can write cleaner components with less ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found