Home > other >  How to display text from async function
How to display text from async function

Time:09-10

I would like to display username get from async function on profile page. Here is my code to get username on user.js.

//assume username is Peter
    async function user_attr() {
        try{
        const { attributes } = await Auth.currentAuthenticatedUser();
        console.log(JSON.stringify(attributes.username)); //output:Peter
        } catch (e) {
            console.log(e);
        }
    }

and I would like display it in Text on profile.js.

import './user.js'
<Text>{username}</Text>

Since async function cannot return value, what should I do to display the username?

CodePudding user response:

You can use the .then .catch approach.

in your function you return the value you need (in this case username):

async function user_attr() {
    try{
    const { attributes } = await Auth.currentAuthenticatedUser();
    const username = JSON.stringify(attributes.username);
    return username;
    } catch (e) {
        console.log(e);
    }
}
export default user_attr;

Then in the file you want to use the username:

import user_attr from './user.js';

let username;

user_attr().then((res) => {
  username = res;
  console.log(username); //output:Peter
)};

CodePudding user response:

To be able to display the returned username on a React component, you have to set the value in a useState() hook. To do that, the API call may be made in a useEffect() hook.

const [userName, setUserName] = useState();

useEffect(() => {
  Auth
    .currentAuthenticatedUser()
    .then((data) => {
      setUserName(JSON.stringify(data.attributes.username));
    })
    .catch((err) => console.error(err));
}, []);

return (
  ...
  <Text>{userName}</Text>
  ...
);
  • Related