Search code examples
salesforcesalesforce-lightning

Error while executing showtoast in salesforce lightning


Below code throws an error while executing toastEvent.setParams statement. Not sure what I have missed or is it deprecated in spring'19 ?

loadContacts : function(cmp) {
    var action = cmp.get("c.getContacts");
    action.setCallback(this, function(response){
        var state = response.getState();
        if (state === 'SUCCESS') {
            cmp.set('v.contacts', response.getReturnValue());
            cmp.set('v.contactList', response.getReturnValue());
            this.updateTotal(cmp);
        }
        console.log('Here');
        var toastEvent = $A.get("e.force:showToast");
        if (state === 'SUCCESS') {
            toastEvent.setParams({
                "title" : 'Success!',
                "message" : 'Your contacts have been loaded successfully.'
            });
        }
        else {
            toastEvent.setParams({
                "title" : "Error!",
                "message" : "Something has gone wrong."
            });
        }
        toastEvent.fire();
    });
    $A.enqueueAction(action);
},

Here is the screenshot of the error: enter image description here


Solution

  • From the docs:

    This event is handled by the one.app container. It’s supported in Lightning Experience, Salesforce app, and Lightning communities.

    That error will pop up when you attempt to grab $A.get("e.force:showToast") outside of the one.app container context (e.g., if you have your component in a Lightning App for testing instead of dragging it on to a record page in the builder). $A.get("e.force:showToast") comes back as undefined, and calling setParams on undefined throws the error.

    Try dragging your component onto a record detail page or a community, or create a tab from the Lighting component. If you need to use the component outside of the one.app context, you'll need to implement the show/hide toast logic yourself.