Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
timolins committed Dec 21, 2024
2 parents b587cf3 + c80d57f commit 7524216
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 14 deletions.
18 changes: 18 additions & 0 deletions site/pages/docs/toast.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,24 @@ toast.promise(
);
```

#### Using an Async Function

You can also provide a function that returns a promise, which will be called automatically.

```js
toast.promise(
async () => {
const { id } = await fetchData1();
await fetchData2(id);
},
{
loading: 'Loading',
success: 'Got the data',
error: 'Error when fetching',
}
);
```

## Default durations

Every type has its own duration. You can overwrite them `duration` with the toast options. This can be done per toast options or globally by the [`<Toaster/>`](/docs/toaster).
Expand Down
2 changes: 1 addition & 1 deletion site/pages/docs/toaster.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ This component will render all toasts. Alternatively you can create own renderer
// Default options for specific types
success: {
duration: 3000,
theme: {
iconTheme: {
primary: 'green',
secondary: 'black',
},
Expand Down
44 changes: 31 additions & 13 deletions src/core/toast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,31 +59,49 @@ toast.remove = (toastId?: string) =>
dispatch({ type: ActionType.REMOVE_TOAST, toastId });

toast.promise = <T>(
promise: Promise<T>,
promise: Promise<T> | (() => Promise<T>),
msgs: {
loading: Renderable;
success: ValueOrFunction<Renderable, T>;
error: ValueOrFunction<Renderable, any>;
success?: ValueOrFunction<Renderable, T>;
error?: ValueOrFunction<Renderable, any>;
},
opts?: DefaultToastOptions
) => {
const id = toast.loading(msgs.loading, { ...opts, ...opts?.loading });

if (typeof promise === 'function') {
promise = promise();
}

promise
.then((p) => {
toast.success(resolveValue(msgs.success, p), {
id,
...opts,
...opts?.success,
});
const successMessage = msgs.success
? resolveValue(msgs.success, p)
: undefined;

if (successMessage) {
toast.success(successMessage, {
id,
...opts,
...opts?.success,
});
} else {
toast.dismiss(id);
}
return p;
})
.catch((e) => {
toast.error(resolveValue(msgs.error, e), {
id,
...opts,
...opts?.error,
});
const errorMessage = msgs.error ? resolveValue(msgs.error, e) : undefined;

if (errorMessage) {
toast.error(errorMessage, {
id,
...opts,
...opts?.error,
});
} else {
toast.dismiss(id);
}
});

return promise;
Expand Down

0 comments on commit 7524216

Please sign in to comment.