Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improvement to toast.promise #22

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 23 additions & 20 deletions src/lib/core/toast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,26 +58,29 @@ toast.promise = <T>(
},
opts?: DefaultToastOptions
) => {
const id = toast.loading(msgs.loading, { ...opts, ...opts?.loading });

promise
.then((p) => {
toast.success(resolveValue(msgs.success, p), {
id,
...opts,
...opts?.success
});
return p;
})
.catch((e) => {
toast.error(resolveValue(msgs.error, e), {
id,
...opts,
...opts?.error
});
});

return promise;
//default to Infinity, so that the loading toast will stay until we have resolved the promise
const id = toast.loading(msgs.loading, { duration: Infinity,
...opts,
...opts?.loading
});
promise
.then((p) => {
// remove the toast explicity, instead of reusing the id with success/error toast. With this we don't need to override the opts of toast.loading for toast.success/toast.error
toast.remove(id)
toast.success(msgs.success ?? p, {
...opts,
...opts?.success
});
return p;
})
.catch((e) => {
toast.remove(id)
toast.error(msgs.error ?? e, {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

p can be an object, right? what if I want to use from the p a specific property?

Example:
p = { errorMessage: "Something went wrong" } - in this case, I want to use p.errorMessage.

Copy link

@arthurparaschiv arthurparaschiv Mar 20, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is already possible - that is the purpose of resolveValue

toast.promise(
  new Promise((resolve) => resolve({
    successMsg: 'Success from promise'
  })),
  {
    loading: 'Laoding',
    success: function(result) {
      return result.successMsg;
    },
    error: 'Error',
  }
)

You can pass a function instead of a string

...opts,
...opts?.error
});
});
return promise;
};

export default toast;