Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

373
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda