Skip to content

An opinionated toast component for React.

Pass promise as callback, export ts types (#26)

Emil Kowalskica9120082728
diff --git a/README.md b/README.md
index 9af04bc..023b8f2 100644
--- a/README.md
+++ b/README.md
@@ -90,6 +90,18 @@ toast.promise(() => new Promise((resolve) => setTimeout(resolve, 2000)), {
});
```
+You can pass a function to the success/error messages to incorporate the result/error of the promise.
+
+```jsx
+toast.promise(promise, {
+ loading: 'Loading...',
+ success: (data) => {
+ return `${data.name} has been added!`;
+ },
+ error: 'Error',
+});
+```
+
### Custom JSX
You can pass jsx as the first argument instead of a string to render custom jsx while maintaining default styling. You can use the headless version below for a custom, unstyled toast.
diff --git a/src/index.tsx b/src/index.tsx
index 153c203..de8fa97 100644
--- a/src/index.tsx
+++ b/src/index.tsx
@@ -4,7 +4,7 @@ import React from 'react';
import './styles.css';
import { getAsset, Loader } from './assets';
-import { HeightT, Position, PromiseData, ToastT, ToastToDismiss } from './types';
+import { HeightT, Position, PromiseData, ToastT, ToastToDismiss, ExternalToast } from './types';
import { ToastState, toast } from './state';
// Visible toasts amount
@@ -26,6 +26,8 @@ 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,6 +75,7 @@ const Toast = (props: ToastProps) => {
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;
@@ -115,25 +118,28 @@ const Toast = (props: ToastProps) => {
}, []);
React.useEffect(() => {
- if (toast.promise) {
+ if (isPromise(toast)) {
setPromiseStatus('loading');
- if (toast.promise instanceof Promise) {
- toast.promise
- .then(() => {
+ const promiseHandler = (promise: Promise<any>) => {
+ promise
+ .then((data) => {
+ if (toast.success && typeof toast.success === 'function') {
+ setPromiseResult(toast.success(data));
+ }
setPromiseStatus('success');
})
- .catch(() => {
+ .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') {
- toast
- .promise()
- .then(() => {
- setPromiseStatus('success');
- })
- .catch(() => {
- setPromiseStatus('error');
- });
+ promiseHandler(toast.promise());
}
}
}, [toast]);
@@ -202,21 +208,19 @@ const Toast = (props: ToastProps) => {
}, [toast.delete]);
const promiseTitle = React.useMemo(() => {
- const isPromise = (toast: ToastT): toast is PromiseData & { id: number } => Boolean(toast.promise);
-
if (!isPromise(toast)) return null;
switch (promiseStatus) {
case 'loading':
return toast.loading;
case 'success':
- return toast.success;
+ return typeof toast.success === 'function' ? promiseResult : toast.success;
case 'error':
- return toast.error;
+ return typeof toast.error === 'function' ? promiseResult : toast.error;
default:
return null;
}
- }, [promiseStatus]);
+ }, [promiseStatus, promiseResult]);
return (
<li
@@ -237,7 +241,7 @@ const Toast = (props: ToastProps) => {
data-index={index}
data-front={isFront}
data-swiping={swiping}
- data-type={toastType}
+ data-type={promiseStatus !== 'loading' ? promiseStatus : toastType}
data-invert={invert}
data-swipe-out={swipeOut}
data-expanded={Boolean(expanded || (expandByDefault && mounted))}
@@ -327,7 +331,9 @@ const Toast = (props: ToastProps) => {
) : null}
<div data-content="">
- <div data-title="">{toast.title ?? promiseTitle}</div>
+ <div data-title="">
+ <>{toast.title ?? promiseTitle}</>
+ </div>
{toast.description ? (
<div data-description="" className={descriptionClassName + toastDescriptionClassname}>
{toast.description}
@@ -515,4 +521,4 @@ const Toaster = (props: ToasterProps) => {
</div>
);
};
-export { toast, Toaster };
+export { toast, Toaster, ToastT, ExternalToast };
diff --git a/src/types.ts b/src/types.ts
index 635614c..6ebb0e7 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -6,8 +6,8 @@ export type PromiseT = Promise<any> | (() => Promise<any>);
export type PromiseData = ExternalToast & {
loading: string | React.ReactNode;
- success: string | React.ReactNode;
- error: string | React.ReactNode;
+ success: string | React.ReactNode | ((data: any) => React.ReactNode | string);
+ error: string | React.ReactNode | ((error: any) => React.ReactNode | string);
};
export interface ToastT {
diff --git a/website/src/components/Types/Types.tsx b/website/src/components/Types/Types.tsx
index 5aeeae6..9e281b5 100644
--- a/website/src/components/Types/Types.tsx
+++ b/website/src/components/Types/Types.tsx
@@ -2,6 +2,8 @@ import React from 'react';
import { toast } from 'sonner';
import { CodeBlock } from '../CodeBlock';
+const promiseCode = '`${data.name} toast has been added`';
+
export const Types = () => {
const [activeType, setActiveType] = React.useState(allTypes[0]);
@@ -76,16 +78,28 @@ const allTypes = [
snippet: `const promise = () => new Promise((resolve) => setTimeout(resolve, 2000));
toast.promise(promise, {
- loading: 'Loading',
- success: 'Success',
+ loading: 'Loading...',
+ success: (data) => {
+ return ${promiseCode};
+ },
error: 'Error',
});`,
action: () =>
- toast.promise(() => new Promise((resolve) => setTimeout(resolve, 2000)), {
- loading: 'Loading',
- success: 'Success',
- error: 'Error',
- }),
+ toast.promise(
+ () =>
+ new Promise((resolve) => {
+ setTimeout(() => {
+ resolve({ name: 'Sonner' });
+ }, 2000);
+ }),
+ {
+ loading: 'Loading...',
+ success: (data) => {
+ return `${data.name} toast has been added`;
+ },
+ error: 'Error',
+ },
+ ),
},
{
name: 'Custom',