Skip to content

An opinionated toast component for React.

Toast promise title (#84)

João Pedro Magalhãesebce3cdd75bf
diff --git a/src/index.tsx b/src/index.tsx
index 4dfc4b0..0d80758 100644
--- a/src/index.tsx
+++ b/src/index.tsx
@@ -5,7 +5,7 @@ import ReactDOM from 'react-dom';
import './styles.css';
import { getAsset, Loader } from './assets';
-import { HeightT, Position, PromiseData, ToastT, ToastToDismiss, ExternalToast, ToasterProps } from './types';
+import { HeightT, Position, ToastT, ToastToDismiss, ExternalToast, ToasterProps } from './types';
import { ToastState, toast } from './state';
// Visible toasts amount
@@ -27,8 +27,6 @@ const SWIPE_TRESHOLD = 20;
const TIME_BEFORE_UNMOUNT = 200;
-const isPromise = (toast: ToastT): toast is PromiseData & { id: number } => Boolean(toast.promise);
-
interface ToastProps {
toast: ToastT;
toasts: ToastT[];
@@ -73,10 +71,8 @@ const Toast = (props: ToastProps) => {
const [removed, setRemoved] = React.useState(false);
const [swiping, setSwiping] = React.useState(false);
const [swipeOut, setSwipeOut] = React.useState(false);
- const [promiseStatus, setPromiseStatus] = React.useState<'loading' | 'success' | 'error' | null>(null);
const [offsetBeforeRemove, setOffsetBeforeRemove] = React.useState(0);
const [initialHeight, setInitialHeight] = React.useState(0);
- const [promiseResult, setPromiseResult] = React.useState<React.ReactNode | string>(null);
const toastRef = React.useRef<HTMLLIElement>(null);
const isFront = index === 0;
const isVisible = index + 1 <= visibleToasts;
@@ -110,7 +106,7 @@ const Toast = (props: ToastProps) => {
}, 0);
}, [heights, heightIndex]);
const invert = toast.invert || ToasterInvert;
- const disabled = promiseStatus === 'loading';
+ const disabled = toastType === 'loading';
offset.current = React.useMemo(() => heightIndex * GAP + toastsHeightBefore, [heightIndex, toastsHeightBefore]);
@@ -138,33 +134,6 @@ const Toast = (props: ToastProps) => {
}
}, [toast.title, toast.description]);
- React.useEffect(() => {
- if (isPromise(toast)) {
- setPromiseStatus('loading');
- const promiseHandler = (promise: Promise<any>) => {
- promise
- .then((data) => {
- if (toast.success && typeof toast.success === 'function') {
- setPromiseResult(toast.success(data));
- }
- setPromiseStatus('success');
- })
- .catch((error) => {
- setPromiseStatus('error');
- if (toast.error && typeof toast.error === 'function') {
- setPromiseResult(toast.error(error));
- }
- });
- };
-
- if (toast.promise instanceof Promise) {
- promiseHandler(toast.promise);
- } else if (typeof toast.promise === 'function') {
- promiseHandler(toast.promise());
- }
- }
- }, [toast]);
-
const deleteToast = React.useCallback(() => {
// Save the offset for the exit swipe animation
setRemoved(true);
@@ -177,7 +146,7 @@ const Toast = (props: ToastProps) => {
}, [toast, removeToast, setHeights, offset]);
React.useEffect(() => {
- if ((toast.promise && promiseStatus === 'loading') || toast.duration === Infinity) return;
+ if ((toast.promise && toastType === 'loading') || toast.duration === Infinity) return;
let timeoutId: NodeJS.Timeout;
// Pause the timer on each hover
@@ -208,7 +177,7 @@ const Toast = (props: ToastProps) => {
}
return () => clearTimeout(timeoutId);
- }, [expanded, interacting, expandByDefault, toast, duration, deleteToast, toast.promise, promiseStatus]);
+ }, [expanded, interacting, expandByDefault, toast, duration, deleteToast, toast.promise, toastType]);
React.useEffect(() => {
const toastNode = toastRef.current;
@@ -230,21 +199,6 @@ const Toast = (props: ToastProps) => {
}
}, [toast.delete]);
- const promiseTitle = React.useMemo(() => {
- if (!isPromise(toast)) return null;
-
- switch (promiseStatus) {
- case 'loading':
- return toast.loading;
- case 'success':
- return typeof toast.success === 'function' ? promiseResult : toast.success;
- case 'error':
- return typeof toast.error === 'function' ? promiseResult : toast.error;
- default:
- return toast.loading;
- }
- }, [promiseStatus, promiseResult]);
-
return (
<li
aria-live={toast.important ? 'assertive' : 'polite'}
@@ -264,7 +218,7 @@ const Toast = (props: ToastProps) => {
data-index={index}
data-front={isFront}
data-swiping={swiping}
- data-type={promiseStatus !== 'loading' && promiseStatus ? promiseStatus : toastType}
+ data-type={toastType}
data-invert={invert}
data-swipe-out={swipeOut}
data-expanded={Boolean(expanded || (expandByDefault && mounted))}
@@ -362,15 +316,13 @@ const Toast = (props: ToastProps) => {
<>
{toastType || toast.icon || toast.promise ? (
<div data-icon="">
- {toast.promise ? <Loader visible={promiseStatus === 'loading'} /> : null}
- {toast.icon || getAsset(promiseStatus ?? toast.type)}
+ {toast.promise ? <Loader visible={toastType === 'loading'} /> : null}
+ {toast.icon || getAsset(toastType)}
</div>
) : null}
<div data-content="">
- <div data-title="">
- <>{toast.title ?? promiseTitle}</>
- </div>
+ <div data-title="">{toast.title}</div>
{toast.description ? (
<div data-description="" className={descriptionClassName + toastDescriptionClassname}>
{toast.description}
@@ -394,9 +346,10 @@ const Toast = (props: ToastProps) => {
{toast.action ? (
<button
data-button=""
- onClick={() => {
+ onClick={(event) => {
+ toast.action?.onClick(event);
+ if (event.defaultPrevented) return;
deleteToast();
- toast.action?.onClick();
}}
>
{toast.action.label}
diff --git a/src/state.ts b/src/state.ts
index 69ac95f..a9d18ee 100644
--- a/src/state.ts
+++ b/src/state.ts
@@ -24,6 +24,10 @@ class Observer {
publish = (data: ToastT) => {
this.subscribers.forEach((subscriber) => subscriber(data));
+ };
+
+ addToast = (data: ToastT) => {
+ this.publish(data);
this.toasts = [...this.toasts, data];
};
@@ -35,16 +39,16 @@ class Observer {
});
if (alreadyExists) {
- this.toasts.map((toast) => {
+ this.toasts = this.toasts.map((toast) => {
if (toast.id === id) {
- this.publish({ ...toast, ...data, id });
- return { ...toast, ...data };
+ this.publish({ ...toast, ...data, id, title: message });
+ return { ...toast, ...data, id, title: message };
}
return toast;
});
} else {
- this.publish({ title: message, ...rest, id });
+ this.addToast({ title: message, ...rest, id });
}
return id;
@@ -74,7 +78,16 @@ class Observer {
};
promise = <ToastData>(promise: PromiseT<ToastData>, data?: PromiseData<ToastData>) => {
- return this.create({ ...data, promise });
+ const id = this.create({ ...data, promise, type: 'loading', message: data.loading });
+ const p = promise instanceof Promise ? promise : promise();
+ p.then((promiseData) => {
+ const message = typeof data.success === 'function' ? data.success(promiseData) : data.success;
+ this.create({ id, type: 'success', message });
+ }).catch((error) => {
+ const message = typeof data.error === 'function' ? data.error(error) : data.error;
+ this.create({ id, type: 'error', message });
+ });
+ return id;
};
// We can't provide the toast we just created as a prop as we didn't creat it yet, so we can create a default toast object, I just don't know how to use function in argument when calling()?
@@ -90,7 +103,7 @@ export const ToastState = new Observer();
const toastFunction = (message: string | React.ReactNode, data?: ExternalToast) => {
const id = data?.id || toastsCounter++;
- ToastState.publish({
+ ToastState.addToast({
title: message,
...data,
id,
diff --git a/src/types.ts b/src/types.ts
index fafad2a..8208d15 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -23,7 +23,7 @@ export interface ToastT {
important?: boolean;
action?: {
label: string;
- onClick: () => void;
+ onClick: (event: React.MouseEvent<HTMLButtonElement>) => void;
};
cancel?: {
label: string;
diff --git a/test/src/app/page.tsx b/test/src/app/page.tsx
index 831c010..07295ae 100644
--- a/test/src/app/page.tsx
+++ b/test/src/app/page.tsx
@@ -34,6 +34,23 @@ export default function Home() {
>
Render Action Toast
</button>
+ <button
+ data-testid="action-prevent"
+ className="button"
+ onClick={() =>
+ toast('My Message', {
+ action: {
+ label: 'Action',
+ onClick: (event) => {
+ event.preventDefault();
+ console.log('Action');
+ },
+ },
+ })
+ }
+ >
+ Render Action Toast
+ </button>
<button
data-testid="promise"
className="button"
diff --git a/test/tests/basic.spec.ts b/test/tests/basic.spec.ts
index 97ae51b..275d3ea 100644
--- a/test/tests/basic.spec.ts
+++ b/test/tests/basic.spec.ts
@@ -58,6 +58,12 @@ test.describe('Basic functionality', () => {
await expect(page.locator('[data-sonner-toast]')).toHaveCount(1);
});
+ test('toast is not removed when event prevented in action', async ({ page }) => {
+ await page.getByTestId('action-prevent').click();
+ await page.locator('[data-button]').click();
+ await expect(page.locator('[data-sonner-toast]')).toHaveCount(1);
+ });
+
test("toast's auto close callback gets executed correctly", async ({ page }) => {
await page.getByTestId('auto-close-toast-callback').click();
await expect(page.getByTestId('auto-close-el')).toHaveCount(1);