Ani
Ani

Reputation: 63

can not retrieve Username with Amplify Auth.currentAuthenticatedUser

forgive my novice question but I am new to AWS amplify ... I started a web app with react and I can log in with Cognito Facebook and Google and also in a normal signup/sign-in form.

Now I want to do the next step and show a welcome message that include the username of the loged-in user... should be very simple : )

i used this function

function checkUser() {  let user = Auth.currentAuthenticatedUser();  alert(user.username)  }

it is not showing me the username! instead it shows the following popup message enter image description here

could anyone please advice how to get it work.. thanks very much in advance : )

sofar my code looks like this

import {Auth} from 'aws-amplify';
function checkUser() {
let user = Auth.currentAuthenticatedUser();
alert(user)  }

function signOut() {
Auth.signOut()
  .then(data => console.log(data))
  .catch(err => console.log(err))
}

function App() {
  return (
    <div className="App">
    <header className="App-header">
    <img src={logo} className="App-logo" alt="logo" />
        <p>
         This site is under Construction
        </p>
        <p>
        <button onClick={() => Auth.federatedSignIn()}>Sign In</button>
        <button onClick={checkUser}>Check User</button>
        <button onClick={signOut}>Sign Out</button>
        </p>
      </header>
    </div>
  );
}
export default App;

Upvotes: 3

Views: 5195

Answers (1)

Horatiu Jeflea
Horatiu Jeflea

Reputation: 7424

It is an async call:

async function checkUser() {
    let user = await Auth.currentAuthenticatedUser();  
    alert(user.username)
}

or

Auth.currentAuthenticatedUser()
    .then(user => alert(user.username))
    .catch(err => console.log(err));

Upvotes: 4

Related Questions