Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

371
Views
How do I use Async with array.map when rendering in ReactJS?

How would I go about running this async with ReactJS?

{array.map((content, index) => {
    const var = await asyncFunction(param)

    return(
        <div key={index} className="someClass">
            <h4 className="anotherClass">{var}</h4>
        </div>
    )
})}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You have to separate the async processing from the rendering (as of React 17, at least), and you have to use the promise directly, but can be done in a function, stored in a state variable, then rendered. That function can be called when the array changes using useEffect.

Example:


function MyComponent(array) {
  const [vars, setVars] = useState([]);

  function handleArrayChanged(newArray) {
    // note: no error handling, do this yourself as appropriate.
    Promise.all(array.map(var => asyncFunction(var)))
      .then((newVars) => setVars(newVars))
      .catch(error => { /* handle error */ });
  }

  useEffect(() => {
    handleArrayChanged(array);
  }, [array]);

  return (
    <>
    {vars.map((var, index) => {
      return(
        <div key={index} className="someClass">
          <h4 className="anotherClass">{var}</h4>
        </div>
      )
    })}
  </>
}

Depending on exactly what asyncFunction does, you may want to break that async check out into its own component, as well, but that's subjective based on what asyncFunction does.


function MyComponent({element}) {
  const [var, setVar] = useState(undefined)

  function handleElementChanged(newElement) {
    asyncFunction(newElement)
      .then(newVar => setVar(newVar))
      .catch(error => { /* handle error */ });
  }

  useEffect(() => {
    handleElementChanged(element);
  }, [element]);

  return (
    <div className="someClass">
      <h4 className="anotherClass">{var}</h4>
    </div>
  );
}

function MyList({array}) {
  return (
   <>
     {array.map(element, index) => (
       <MyComponent 
         key={index}
         element={element}
       />
     )}
   </>
  );
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!