Lightning Aura Components – Control Flow Finish Behavior Not Working as Expected

By default, a new instance of the flow (interview) is created after a flow is finished and it lands in the first screen again. To control this behavior, we can embed the flow inside aura component as suggested in the article here.

Here is my Aura component code to implement this functionality.

<aura:component implements="flexipage:availableForAllPageTypes" access="global">
    <aura:attribute name="flowNotCompleted" type="Boolean" default="true" />
    <aura:handler name="init" value="{!this}" action="{!c.init}" />
    <aura:renderIf isTrue="{!v.flowNotCompleted}">
        <lightning:flow aura:id="flowData" onstatuschange="{!c.handleStatusChange}" />
    </aura:renderIf>
</aura:component>

Here is my controller,

({
    init : function (component) {
        // Find the component whose aura:id is "flowData"
        var flow = component.find("flowData");
        // In that component, start your flow. Reference the flow's API Name.
        flow.startFlow("Hello_World");
    },
    handleStatusChange : function (component, event) {
        if(event.getParam("status") === "FINISHED") {
            // Hide it
            component.set("v.flowNotCompleted", false);
        }
    },
})

Basically, I am trying to hide the flow element after it is finished and is working as expected. But when I monitor the debug logs, I see a new instance of the flow is getting created and the flow lands at the first screen even though it is not visible in the UI. In my actual implementation, the flow involves making callouts and other complex logic before showing the first screen which we don't want to execute unnecessarily. We do not want to redirect or move to some other page as well.

So what is the clean way to finish the flow without starting another interview?

Best Answer

You cannot create the visual flow at run time, meaning drop the flow only when your flowNotCompleted is true. To achieve this you can use $A.createComponent which will create another Aura component and be placed in init method. Lets call it as child component with name as 'flowCarrier.cmp'

Now we need a way to destroy the dynamically created aura component can use cmp.destroy(); method (check the last section of the same documentation link)

Documentation for dynamic component creation

So when a your flow completes, in the handleStatusChange's FINISHED status, you can pass an application event to the parent component to destroy the child component making the flow go away.

Related Topic