Current User information for React using React Hooks
See original GitHub issueWhen 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 withwithAuthenticator
- 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…
- Is there a more efficient or direct way to access the current user than to call an async function (
Auth.currentAuthenticatedUser()
)? - 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.
- Should a component (other than App) specify
true
forbypassCache
to be more efficient? (Since the App tag is likely going to havebypassCache
set tofalse
.) - Should authentication information be placed in a Context for components to access? (Should this be something that Amplify does out of the box?)
- If the App component is being wrapped with
withAuthenticator
, then should any other child component really need to be wrapped withwithAuthenticator
? (No, right?)
Issue Analytics
- State:
- Created 5 years ago
- Reactions:5
- Comments:8 (1 by maintainers)
Top 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 >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
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, thenusername
andsub
values match up.@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.