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
CodePudding user response:
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);
};
CodePudding user response:
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])
}
}
}