Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

375
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda