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

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

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 Denunciar

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 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