Skip to content
Advertisement

Access value from Promise for HTML Element

I’m new to React and javascript and need some help. I’m using a function that returns a Promise including an interface. I want to access the variable in the Interface and apply it in <dl><dt>{//string variable}</dt></dl>.

The problem is that I’m only getting a Promise object, and I need it as a string. How can I do this?

This is my async function for getting the Promise object and using it:

async function getName() {
  const res = await getNamePromise(); // type: Promise<Interface>
  console.log(res.name);
}

export function userInfo(){
return(
<dl>
    <dd>{// need a string variable}</dd>
</dl>
);
} 

When is write it like this: getName().then((name) => console.log(name)); name is a string. But how can I store this as a string variable and use it?

Advertisement

Answer

You’re using React, so you should put api call and html tag into a react component, and save the api response data with component state to trigger re-render, try this:

function NameComponent() {
  React.useEffect(() => {
    async function getName() {
      const res = await getNamePromise(); // type: Promise<Interface>
      setName(res.name)
    }

    getName()
  }, [])

  React.useEffect(() => {
    async function getPhoto() {
      const res = await getPhotoPromise(); // type: Promise<Interface>
      setPhoto(res.photo)
    }

    getPhoto()
  }, [])

  const [name, setName] = React.useState()
  const [photo, setPhoto] = React.useState()

  if (!name || !photo) {
    return <div>Loading...</div>
  }

  return(
    <dl>
      <dd>{name}</dd>
      <dd>{photo}</dd>
    </dl>
  );
} 
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement