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

118
Views
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 answers
Answer question

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 Report

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