Skip to content

Commit

Permalink
Merge pull request #89 from bpingris/fix/toast-dot-promise-rejected
Browse files Browse the repository at this point in the history
fix: await the promise to be able to catch its error and a toast
  • Loading branch information
gunnartorfis authored Sep 14, 2024
2 parents 1a3f524 + 671fb5d commit 02e3915
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 29 deletions.
21 changes: 19 additions & 2 deletions example/src/ToastDemo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -97,13 +97,30 @@ export const ToastDemo: React.FC = () => {
/>
<Button title="Show outside of a React component" onPress={handleToast} />
<Button
title="Toast with a promise"
title="Toast with a successful promise"
onPress={() => {
toast.promise(
new Promise((resolve) => {
setTimeout(() => {
resolve('Promise resolved');
}, 7000);
}, 2000);
}),
{
loading: 'Loading...',
success: (result: string) => `Promise resolved: ${result}`,
error: 'Promise failed',
}
);
}}
/>
<Button
title="Toast with a failed promise"
onPress={() => {
toast.promise(
new Promise((_, reject) => {
setTimeout(() => {
reject('Promise rejected');
}, 2000);
}),
{
loading: 'Loading...',
Expand Down
59 changes: 32 additions & 27 deletions src/toast.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -189,44 +189,49 @@ export const Toast = React.forwardRef<ToastRef, ToastProps>(
);

React.useEffect(() => {
if (isResolvingPromise.current) {
return;
}
const handlePromise = async () => {
if (isResolvingPromise.current) {
return;
}

if (promiseOptions?.promise) {
try {
if (promiseOptions?.promise) {
isResolvingPromise.current = true;
promiseOptions.promise.then((data) => {

try {
await promiseOptions.promise.then((data) => {
addToast({
title: promiseOptions.success(data) ?? 'Success',
id,
variant: 'success',
promiseOptions: undefined,
});
});
} catch (error) {
addToast({
title: promiseOptions.success(data) ?? 'Success',
title: promiseOptions.error ?? 'Error',
id,
variant: 'success',
variant: 'error',
promiseOptions: undefined,
});
} finally {
isResolvingPromise.current = false;
});
} catch (error) {
addToast({
title: promiseOptions.error ?? 'Error',
id,
variant: 'error',
promiseOptions: undefined,
});
isResolvingPromise.current = false;
}

return;
}

return;
}
if (duration === Infinity) {
return;
}

if (duration === Infinity) {
return;
}
// Start the timer only if it hasn't been started yet
if (!timerStart.current) {
timerStart.current = Date.now();
startTimer();
}
};

// Start the timer only if it hasn't been started yet
if (!timerStart.current) {
timerStart.current = Date.now();
startTimer();
}
handlePromise();
}, [
duration,
id,
Expand Down

0 comments on commit 02e3915

Please sign in to comment.