Home > Blockchain >  How can I call an ASYNC function inside of .map for populating a table in REACT?
How can I call an ASYNC function inside of .map for populating a table in REACT?

Time:11-30

I am trying to call an async function using .map() in REACT to populate table data cells. The async function is calling the backend of my application using data from the array that is being iterated through.

The function that is being called returns a number when called properly. This is my first time posting a question so any help is great! If I need to add more information I will.

Thank you.

{tableInfo.map(info => (
      <tr>
        <td key={info.name}>{info.name}</td>
        <td key={info.price}>{info.price}</td>
        <td key={info.amount}>{info.amount}</td>
        <td>
          {async () => await fetchCurrentPrice.getPrice(info.name)}
        </td>
      </tr> ))}

CodePudding user response:

async functions always return promises. You can't fetch data asynchronously during rendering.

You need a useEffect hook to run the function which gathers the data, and then a useState hook to store it, along with logic to show a loading state while you wait for it.

const MyRow = ({ info }) => {
   const [currentPrice, setCurrentPrice] = useState(null);

   useEffect(() => {
       fetchCurrentPrice.getPrice(info.name).then(setCurrentPrice);
   }, [info]);

   return <tr>
        <td key={info.name}>{info.name}</td>
        <td key={info.price}>{info.price}</td>
        <td key={info.amount}>{info.amount}</td>
        <td>{currentPrice ?? <Loading />}</td>
   </tr>

}

with

{tableInfo.map(info => <MyRow key={info.name} info={info} />)}

CodePudding user response:

Use a separate component for the tr tag and call it within it.

const Component = (props) => {
  const {info} = props
  
  useEffect(() => {
    // call your api and set it to state
  }, [])
  
  return <tr>
        <td key={info.name}>{info.name}</td>
        <td key={info.price}>{info.price}</td>
        <td key={info.amount}>{info.amount}</td>
        <td>
          {async () => await fetchCurrentPrice.getPrice(info.name)}
        </td>
      </tr>
}

{tableInfo.map(info => <Component info={info} />)}
  • Related