简体   繁体   中英

How to display group of a user authenticated using Cognito using React?

I have a app running on amplify which is authenticated using Cognito. I am trying to display the user's group (render). I have the following code to get the user's information.

export const getCurrentUser = async () => {
  try {
    const userInfo = await Auth.currentAuthenticatedUser({bypassCache:true})
    console.log("User info: ",userInfo)

    if(userInfo){

      return userInfo.signInUserSession.idToken.payload["cognito:groups"];
        }
      }

  catch (err) {
    console.log('error: ', err)
  }
}

And then the app function

function App() {

  
  return (

    <Authenticator formFields={formFields} components={components}>
      
      {({ signOut, user }) => (

        <div className="App">
          <p>
                                                             --> This does not work
            Hey {user.username}, Welcome to NUBER. You are a {getCurrentUser()[0]}
          </p>
          <button onClick={signOut}>Sign out</button>
        </div>
      )}
    </Authenticator>
  );
}

export default App;

How can I render the user's group to the screen?

Your getCurrentUser function is an async/await promise so you need to handle the output asynchronously.

Here's an example:

function App() {
  const [groups, setGroups] = useState([]);

  useEffect(() => {
    const getGroups = async () => {
      const groups = await getCurrentUser();
      setGroups(groups);
    }

    // make sure to catch any error
    getGroups().catch(console.error);
  });

  
  return (

    <Authenticator formFields={formFields} components={components}>
      
      {({ signOut, user }) => (

        <div className="App">
          <p>
            Hey {user.username}, Welcome to NUBER. You are a {groups[0]}
          </p>
          <button onClick={signOut}>Sign out</button>
        </div>
      )}
    </Authenticator>
  );
}

export default App;

Just keep in mind that you need to handle async operations inside use effects differently. Here's a post about it, but there are many others online.

https://devtrium.com/posts/async-functions-useeffect

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM