EDIT: I originally left out a part of my code which I thought was irrelevant to the question but on further investigation realized it was the source of the issue. Adding it in and then will also add the answer.
I was actually calling handleReleaseHold()
instead of directly calling doReleaseHoldRequest()
as I mentioned
I am trying to display a toast notification in Lightning Experience with the results of an API callout from my JS file. I'm not getting an error, but no toast is displaying. Makes me think that it’s an issue of event bubbling/listening from within the JS fetch method, but I haven’t been able to figure it out.
import { LightningElement, track, api, wire } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class HoldModal extends LightningElement {
@track accountId = '001P000001OUxqZIAT';
@track msgToDisplay = 'default';
/// Added in this section - start
handleReleaseHold(){
this.doReleaseHoldRequest();
this.doCloseModal();
}
doCloseModal() {
const buttonPressed = "save";
const closeModalEvent = new CustomEvent('modalClosed', { detail: buttonPressed });
this.dispatchEvent(closeModalEvent);
}
/// Added in this section - end
doDisplayToastMsg(variant, title, message) {
const toastEvt = new ShowToastEvent({
variant: variant,
title: title,
message: message,
});
this.dispatchEvent(toastEvt);
}
doReleaseHoldRequest(){
const url = 'https://www.url.com';
const params = {
method: 'POST',
headers: {
"Content-Type" : "application/json",
"Authorization" : "Token token=xxxxxxxxxxxxxxxxxxx"
},
body: '{"key": "value"}'
};
const thisReference = this; // different this scope when called from within subfunctions, so setting variable here to use correct this
fetch(url, params)
.then((response) => response.json())
.then(function(data){
if(data.message){
// handle later
}
else if(data.errors){
// 1. // console.log('thisReference.accountId: ' + thisReference.accountId);
// 3. // thisReference.doDisplayToastMsg('error', 'within fetch', 'this is the error');
console.log('thisReference.msgToDisplay - before: ' + thisReference.msgToDisplay);
// 4. // thisReference.msgToDisplay = 'MESSAGE INSIDE FETCH';
console.log('thisReference.msgToDisplay - after: ' + thisReference.msgToDisplay);
// 4.a. // thisReference.doDisplayToastMsg('error','within fetch',thisReference.msgToDisplay);
/* 5. const toastEvt = new ShowToastEvent({
variant: 'error',
title: 'title',
message: 'message',
});
thisReference.dispatchEvent(toastEvt);
*/
}
})
.then(function(){
// 6. //thisReference.doDisplayToastMsg('error','last then before catch' ,thisReference.msgToDisplay);
})
.catch(function(error){
console.log('doReleaseHoldRequest error: ' + error);
})
// 2. // thisReference.doDisplayToastMsg('error','after fetch', 'this is the error');
// 4.b. // thisReference.doDisplayToastMsg('error','after fetch',this.msgToDisplay);
}
}