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

121
Visualizações
How to do multiple requests on a map and catch all errors with React?

I have an app in which I'm getting some posts from the user and I'm then pushing each of them into a GitHub repo. However, I would like to catch all the errors that might come from this map. How could I achieve that? Currently my useState is, of course, replacing the previous state there and I'm unsure on how to proceed. Here's the code:

const [errors, setErrors] = useState<string[]>([])

const triggerPostsBackup = (postsData) => {
  posts.map(async (post) => {
    try {
     await THE_REQUEST
    } catch (error) {
      const errorString = `${post.title} failed to upload!`
      setErrors(errors.concat(errorString))
    }
  }
}

Any suggestions?

I've also tried to set an inner variable to keep all the errors and, at the end of the map, use a useState to create the state for my errors but I completely failed there

about 4 years ago · Santiago Gelvez
2 Respostas
Responde à pergunta

0

You can use Promise.allSettled to capture the result of each request. Then, after all requests are complete, you can reduce over them, pushing rejected promises into an error array. Then finally, call setErrors.

const [errors, setErrors] = useState<string[]>([]);

const triggerPostsBackup = async (postsData) => {
  const results = await Promise.allSettled(
    posts.map(async (post) => {
      await THE_REQUEST;
    })
  );

  const errors = results.reduce<string[]>((acc, next, index) => {
    if (next.status === 'rejected') {
      acc.push(`${posts[index].title} failed to upload!`);
    }
    return acc;
  }, []);

  setErrors(errors);
};
about 4 years ago · Santiago Gelvez Relatório

0

Found a solution to my issue. I was able to solve it with a callback (documentation) and it looks like this:

const [errors, setErrors] = useState<string[]>([])

const triggerPostsBackup = (postsData) => {
  posts.map(async (post) => {
    try {
     await THE_REQUEST
    } catch (error) {
      const errorString = `${post.title} failed to upload!`
      setErrors((previousState) => [...previousState, errorString])
    }
  }
}
about 4 years ago · Santiago Gelvez 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