0

I have a delay function in a lighting component helper from which I want to call another function I get the error [this.displayToast is not a function] how do I achieve this?

Delay function:

 callbackOnceAfterDelay : function(cmp, helper){
            var delay=60000; //1 min
            setTimeout(function() {
                console.log('Inside delay: ');
                        this.displayToast(cmp, 'success', 'Thanks');     
            }, delay);},

Function to call:

   displayToast: function(cmp, type, message, messageTemplate, templateData) {
        var toastEvent = $A.get('e.force:showToast');
        toastEvent.setParams({
            type: type,
            message: message,
            messageTemplate: messageTemplate,
            messageTemplateData: templateData
        });
        toastEvent.fire();
    }
  • callbackOnceAfterDelay and displayToast Is it a controller or a helper method? – Pranay Jaiswal Jun 20 '19 at 16:52
3

I think this should do it:

callbackOnceAfterDelay : function(cmp, helper) {
    const self = this;
    const delay=60000; //1 min
    setTimeout(function() {
        console.log('Inside delay: ');
        self.displayToast(cmp, 'success', 'Thanks');     
    }, delay);
},

Just like in normal JS inside the setTimeout function this is not the helper context anymore. At least that is the explanation my limited JS knowledge can provide.

Unsure if the setTimeout will work without $A.getCallback to queue it up in lightning.

callbackOnceAfterDelay : function(cmp, helper) {
    const self = this;
    const delay=60000; //1 min
    window.setTimeout($A.getCallback(function() {
        console.log('Inside delay: ');
        self.displayToast(cmp, 'success', 'Thanks');     
    }), delay);
},
| improve this answer | |
  • +1 You need $A.getCallback whenever you need to do something in the Aura life cycle asynchronously (in this case, we're firing a toast asynchronously), so yes, it is required in this case. – sfdcfox Jun 20 '19 at 12:46
  • @sfdcfox In this case it worked without the $A.getCallback. – Thomas Jun 20 '19 at 13:06
  • 1
    @Thomas No, if you don't use $A.getCallback, your event will get "stuck" until the next time an Aura event fires properly. You should use $A.getCallback to avoid this problem. – sfdcfox Jun 20 '19 at 13:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.