force:closeQuickAction Not Working – How to Fix

I'm new to Salesforce lightning. I'm trying to build a quick action that performs backend logic based on a condition else display a toast. I have created the component and associated it to an object based quick action. Now, after invoking the toast event, I'm trying to close the quickAction modal popup using $A.get("e.force:closeQuickAction").fire(); This doesn't seem to work.

So, I have removed the controller logic and just added that one line and it still doesn't work.

({
    doInit : function(component, event, helper) {
        $A.get("e.force:closeQuickAction").fire();
    }
})

Requesting to guide me on this. Thanks!

Best Answer

The reason why it is working when invoked in callback code because there is modal listener ready for the event and then modal listener can close the model.

But if you write your logic on doInit ( I assume you are registering with init event) then there is no modal which is listening. So modal will not be able to close.

If I am not wrong here you want to run some apex logic and not show modal to user since you don't have anything to show to user.

I would suggest show the modal with some message saying that "YOUR XYZ OPERATION is in progress."

As the modal is completely loaded you can fire close event upon which modal will get closed.

Note: You can destroy the component in doInit but it will only destroy contents of modal not the component, so its better to go with the solution where you can let user know some action is going on.

Another Update (Date : Aug 2019) If you are required to close the modal in init without making any server call then you can simulate async call nature by

setTimeout(()=>{
           let quickActionClose = $A.get("e.force:closeQuickAction");
           quickActionClose.fire();
        },1000);

This will make sure that component is loaded and ready to listen for close event.