diff --git a/example/src/ToastDemo.tsx b/example/src/ToastDemo.tsx index ffdc200..3be94c1 100644 --- a/example/src/ToastDemo.tsx +++ b/example/src/ToastDemo.tsx @@ -97,13 +97,30 @@ export const ToastDemo: React.FC = () => { /> { toast.promise( new Promise((resolve) => { setTimeout(() => { resolve('Promise resolved'); - }, 7000); + }, 2000); + }), + { + loading: 'Loading...', + success: (result: string) => `Promise resolved: ${result}`, + error: 'Promise failed', + } + ); + }} + /> + { + toast.promise( + new Promise((_, reject) => { + setTimeout(() => { + reject('Promise rejected'); + }, 2000); }), { loading: 'Loading...', diff --git a/src/toast.tsx b/src/toast.tsx index 2d53be7..37d7296 100644 --- a/src/toast.tsx +++ b/src/toast.tsx @@ -189,44 +189,49 @@ export const Toast = React.forwardRef( ); 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,