1

On clicking save button in a modal, a JS function is executed:

  saveModal() {
    this.openModal = false;
    markImportant({ Id: this.row.Id })
      .then(this.showToast("success"))
      .catch(this.showToast("error"));
  }

markImportant is a Apex controller method:

@AuraEnabled
public static void markImportant(String Id){
    Account acc = new Account();
    acc.id = Id;
    acc.ImportantField__c = true;
    update acc;
}

showToast is a method used to display toasts:

    showToast(variant) {
    const event = new ShowToastEvent({
      title: "Get Help",
      message:
        "Salesforce documentation is available in the app. Click ? in the upper-right corner.",
      variant: variant
    });
    this.dispatchEvent(event);
  }

I am getting both Error and Success toasts - all executed at once. I presume that the promise returns both success and error? Could you point out my error please?

enter image description here

1 Answer 1

2

Both then() and catch() methods take a callback as input parameter, but you're passing just the value (undefined) returned by showToast() to both. Indeed you're explicit calling showToast() two times, that's why you see both toast messages.

You could use an arrow function to handle the data returned by a promise (in then()) or the exception (in catch()).

You should change your code to:

saveModal() {
    this.openModal = false;
    markImportant({ Id: this.row.Id })
      .then(() => {
          this.showToast("success");
      })
      .catch(() => {
          this.showToast("error");
      });
}

This way the showToast() method will be called only once the promise is settled.

1
  • Thanks, time to learn some more JS.
    – DevelBase2
    Mar 13, 2022 at 11:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .