[SalesForce] Refresh the page after the lightning component

I have a lightning component that shows as button on the record page like below

enter image description here

The lightning component Controller are like below

<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId" access="global"  controller="setCaseClose">
    <aura:attribute name="updateCase" type="Case" default="{'sobjectType':'Case'}"/>
    <lightning:button variant="brand" label="Close Case" onclick="{!c.updateCaseClose}"  />
</aura:component>

Controller

({
    updateCaseClose : function(c, e, h) {
        h.updateCaseClose_helper(c,e,h);
    },
})

Helper

({
    updateCaseClose_helper : function(c,e,h) {
        var action = c.get("c.updateCheck");
        action.setParams({caseId: c.get('v.recordId')});
         $A.enqueueAction(action);
         $A.get('e.force:refreshView').fire();
    }
  })

Apex Class

public class setCaseClose {
    @AuraEnabled
    public static void updateCheck(String caseId){
        List<Case> records = [select id,Status from Case WHERE Id = :caseId];
        for (Case record : records)
        {
            record.Status = 'Closed';
        }
        update records;     
    }
}

On click of the button it doesnt refresh the page and shows the updated Status. I have to manually refresh the page. I did try to add the $A.get('e.force:refreshView').fire(); in the helper it doesnt work

Best Answer

For force:refreshView to work, you need to wait until your apex class returns; before this, the changes haven't been committed to the database yet. We use setCallback to accomplish this task.

({
  updateCaseClose_helper: function(c, e, h) {
    var action = c.get("c.updateCheck");
    action.setParams({ caseId: c.get("v.recordId") });
    action.setCallback(this, result => {
      switch (result.getState()) {
        case "SUCCESS":
        case "DRAFT":
          $A.get("e.force:showToast")
            .setParams({
              title: "Success",
              type: "success",
              message: "This case is now closed."
            })
            .fire();
          break;
        default:
          $A.get("e.force:showToast")
            .setParams({
              title: "Error",
              type: "error",
              message: "An error occurred while saving changes."
            })
            .fire();
      }

      $A.get("e.force:refreshView").fire();
    });
    $A.enqueueAction(action);
  }
})
Related Topic