Properly handle execeptions thrown by Promises in the usePromise() hook (#21408)

This commit is contained in:
Jon Koops 2023-07-03 15:43:08 +02:00 committed by GitHub
parent ee205c8fbc
commit 0e441b9fb8
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -52,15 +52,23 @@ export function usePromise<T>(
const { signal } = controller;
async function handlePromise() {
const value = await factory(signal);
// Try to resolve the Promise, if it fails, check if it was aborted.
try {
callback(await factory(signal));
} catch (error) {
// Ignore errors caused by aborting the Promise.
if (error instanceof Error && error.name === "AbortError") {
return;
}
if (!signal.aborted) {
callback(value);
// Rethrow other errors.
throw error;
}
}
handlePromise();
// Abort the Promise when the component unmounts, or the dependencies change.
return () => controller.abort();
}, deps);
}