Skip to content

Commit

Permalink
Merge pull request #301 from kagurazaka-0/feat-toast-promise-async-func
Browse files Browse the repository at this point in the history
feat: `toast.promise(async () => {})`
  • Loading branch information
timolins authored Dec 21, 2024
2 parents 0b7f086 + 1550a0f commit c80d57f
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
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
6 changes: 5 additions & 1 deletion src/core/toast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ 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>;
Expand All @@ -69,6 +69,10 @@ toast.promise = <T>(
) => {
const id = toast.loading(msgs.loading, { ...opts, ...opts?.loading });

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

promise
.then((p) => {
const successMessage = msgs.success
Expand Down

0 comments on commit c80d57f

Please sign in to comment.