简体   繁体   中英

get data from promise

I have some rest api, and need to get data from promise and render it.

const data = http.get(url) // it return the promise.

// [[PromiseState]]: "fulfilled"
// [[PromiseResult]]: Array(4)

I can console log needed data:

const data = http.get(url).then(res=> console.log(res.data)) // array in console

I read some tutorials, and allways, always it shows how to console log results, but I dont need it in concole, I need render it in component. It may be simple question, but im total new in JS.

const ItemsList = () => {
  const data = http.get(url) //return promise. How can I get array from thid promise result?
  return (
      <ul>
        { data.map(item => {
          return (
            <ItemPreview key={item.id} item={item} />
          );
        })}
      </ul>
  )
}

export default ItemsList

tried async/await. spend already 4 hours to this task, but get only errors. Just don't kwnow how to write it. can someone help, and show me how to do it. Or give me link where I can find how to render promise result in component?

async / await is the way to go

const ItemsList = async () => {
  const data = await http.get(url) 
  return (
      <ul>
        { data.map(item => {
          return (
            <ItemPreview key={item.id} item={item} />
          );
        })}
      </ul>
  )
}

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