So, you are looking for the easiest way to automatically refresh a single Lightning Component without having the need to refresh all the Lightning Components on the screen all at once?

You might have already seen how simple it is to refresh all the components using $A.get('e.force:refreshView').fire();, however, this might be a little overkilled if you just want a very specific component to always refresh in order to show the latest information all the time?

So, here I am going to show you what you can do to make sure you are only refreshing the component that you need to refresh.

Without further ado, let's get into it!

1. Create a Lightning Component

Let's name our Lightning Component AllAccountListView for demonstration purpose. This component will display a ListView component with auto-refresh mechanism.

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes" access="global" >
    <aura:handler name="init" value="{!this}" action="{!c.onInit}"/>
    {!v.body} 
</aura:component>

2. Set up the controller.js

Essentially, the controller will call the helper method to initialize the components (which we will be seeing in the next step). For every 10000 milliseconds (10 seconds), the helper method will be called again and again.

({
    onInit: function (component, event, helper) {
        helper.createAllAccountListListView(component, event, helper);
        window.setInterval(
            $A.getCallback(function() {
				helper.createAllAccountListListView(component, event, helper);
            }), 10000
        );    
    }
})

3. Set up the helper.js

Lastly, the helper method will reset v.body and recreate the component again.

({
    createAllAccountListListView : function(component, event, helper) {
        component.set('v.body', []);
        $A.createComponent(
            "lightning:listView",
            {
                "aura:id": "allAccountListViewId",
                "objectApiName": "Account",
                "listName": "AllAccount",
                "rows" : 10,
                "showActionBar" : false,
                "enableInlineEdit" : false,
                "showRowLevelActions" : false
            },
            function(newListView, status, errorMessage){
                //Add the new button to the body array
                if (status === "SUCCESS") {
                    var body = component.get("v.body");
                    body.push(newListView);
                    component.set("v.body", body);                            
                } else {
                    console.log("Status: " + status + ", " + errorMessage);
                } 
            }
        );
    }
})

Now, your component should be refreshed in every 10 seconds.

Find out more about $A.createComponent.


That's all! Hope this post helps!

Post was published on , last updated on .

Like the content? Support the author by paypal.me!