1

Having trouble figuring out how to get this below code to work in javascript/react;

findSupplierName(supplierId) {
   var object = this.state.supplierData.find(e => e.id === supplierId).name;
   return object;
}

I have two API calls returning arrays, one contains orders while the other contains supplier information. I'm trying to find the supplier_id from the order array into a name from the supplier array.

<tbody>
   {this.state.data.map((data, i) =>
   <tr key={i}>
     <td>{data.id}</td>
     <td>{this.findSupplierName(data.supplier_id)}</td>
     <td>{data.date}</td>
     <td>{data.total}</td>
   </tr>)}
</tbody>

I've tried using async/await but haven't been able to figure it out (Javascript newbie here). Most of the time the code fails as the find function takes a while to find the info.

0

1 Answer 1

0

Reason JavaScript's map function works with an array, and initially this.state.data are undefined until it gets response from ajax request.

you must switch async: false. then the requested data will be recieved and the rest of the code will run right after the data is recieved.

1
  • The function that calls the api and stores the data into this.state.data is already using async and that isn't the problem, rather it's the findSupplierName function which needs to use async/await in order to wait for the result before returning it. Thats the part i can't figure out.
    – MrPaza
    Jul 23, 2018 at 1:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.