2

For lightning I used a handler for force:showToast event to capture toasts for edit/new actions on standard pop up when a record was edited/inserted. I would like to do the same in lwc.

I added a listener in the constructor and it works well only for my custom toasts, but doesn't work for standard toasts when I open a standard pop up. Is there a way to capture standard toasts in lwc?

constructor() {
    super();
    document.addEventListener('lightning__showtoast', this.handleToastEvent.bind(this))
}

handleToastEvent (){
    console.log('toast')
}

Pop up is opened through NavigationMixin.Navigate

handleEditRecord(row) {
  this[NavigationMixin.Navigate]({
      type: 'standard__recordPage',
      attributes: {
          'recordId': row.Id,
          'actionName': 'edit'
      },
  })
}  
1

1 Answer 1

0

If you look at the documentation, to programmatically register your event listener you need to do the following in your "parent" LWC (an ancestor of the LWC generating the show toast event):

constructor() {
    super();

    this.template.addEventListener('lightning__showtoast', this.handleToastEvent.bind(this));
}

I tried this in a playground but the playground doesn't appear to correctly support toasts. It therefore looks like an exercise for the OP to see if this works.

I would assume you would need to provide a component that wraps all the others (perhaps via a "slot") in the page in order to catch "standard" toasts from these components, but I don't think you can catch toasts from the "chrome" of the page outside the body content.

3
  • I have only 1 component, so it is already parent. I tried your code, but standard toast event was not captured. Feb 29, 2020 at 10:00
  • Any feedback on this?
    – jm.
    Oct 12, 2020 at 9:00
  • If there's only one component that is "already the parent" then adding the event listener around the whole template should mean you can capture the toast events from any embedded standard components. If this isn't working you could consider ensuring that the "parent" component includes a div or something similar as a child of the outer-most template that contains everything else, and add the event listener to that element instead.
    – Phil W
    Oct 12, 2020 at 9:45

You must log in to answer this question.

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