function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Jon-Michael Murphey 2Jon-Michael Murphey 2 

automatically refresh Lightning component after file has been uploaded

I have two Aura components, one allows for the upload of a file the other is basically a related list view. I have formatting and other requirements needed to use these instead of OOTB related lists. Im needing the components to refresh after the file has been uploaded so that the list view shows the new file withour havinf to hit F5 or refresh the page. see code below:

Here is the upload cmp:
<aura:component controller="SimplyfyFilesCntrl" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >  
   <aura:handler name="init" value="{!this}" action="{!c.doInit}"/> 
   <aura:handler event="force:refreshView" action="{!c.doInit}" />
   <aura:attribute name="files" type="ContentDocument[]"/>  
   <aura:attribute name="recordId" type="string"/>  
   <aura:attribute name="accept" type="List" default="['.jpg', '.jpeg','.pdf','.csv','.xlsx']"/>  
   <aura:attribute name="multiple" type="Boolean" default="true"/>  
   <aura:attribute name="disabled" type="Boolean" default="false"/>  
   <div class="slds">  
     <div style="border-left: 1px solid rgb(221, 219, 218);  
           border-right: 1px solid rgb(221, 219, 218);  
           border-bottom: 1px solid rgb(221, 219, 218);  
           border-top: 1px solid rgb(221, 219, 218);">  
       <div class="slds-page-header" style="border-radius: 0px; border-right: 0px;border-left: 0px;border-top: 0px;  
                          box-shadow: 0 0px 0px 0 rgba(0, 0, 0, 0.1);">  
         Procedure Files  
       </div>
       <div class="slds-grid">  
         <div class="slds-col slds-size--5-of-12">
                    <lightning:helptext content="Enter the name of the file and upload or to keep the original name of the file just drag or upload file." class="customIcon"/>
           <lightning:input type="text" name="input1" label="Enter File Name" aura:id="fileName" />
         </div>&nbsp; &nbsp;

         <div class="slds-col slds-size---of-12">  
           <lightning:fileUpload label="" multiple="{!v.multiple}"   
                      accept="{!v.accept}" recordId="{!v.recordId}"   
                      onuploadfinished="{!c.UploadFinished}"/>  
         </div>  
       </div><br/>  
     </div>  
   </div>  
 </aura:component>
JS:
({  
   doInit:function(component,event,helper){  
     var action = component.get("c.getFiles");  
     action.setParams({  
       "recordId":component.get("v.recordId")
        
     });
     action.setCallback(this,function(response){  
       var state = response.getState();  
       if(state=='SUCCESS'){  
         var result = response.getReturnValue();  
         console.log('result: ' +result);  
         component.set("v.files",result);
           
       }  
     });  
     $A.enqueueAction(action);
   } ,  
   //Open File onclick event  
   OpenFile :function(component,event,helper){  
     var rec_id = event.currentTarget.id;  
     $A.get('e.lightning:openFiles').fire({ //Lightning Openfiles event  
       recordIds: [rec_id] //file id  
     });  
   },  
   UploadFinished : function(component, event, helper) {  
     var uploadedFiles = event.getParam("files");  
     var documentId = uploadedFiles[0].documentId;  
     var fileName = uploadedFiles[0].name;  
     helper.UpdateDocument(component,event,documentId);  
     var toastEvent = $A.get("e.force:showToast");  
     toastEvent.setParams({  
       "title": "Success!",  
       "message": "File "+fileName+" Uploaded successfully."  
     });  
     toastEvent.fire();
     /* Open File after upload  
     $A.get('e.lightning:openFiles').fire({  
       recordIds: [documentId]  
     });*/  
   },  
 })

Helper:
({  
       UpdateDocument : function(component,event,Id) {  
     var action = component.get("c.UpdateFiles");  
     var fName = component.find("fileName").get("v.value");  
     //alert('File Name'+fName);  
     action.setParams({"documentId":Id,  
              "title": fName,  
              "recordId": component.get("v.recordId")  
              });  
     action.setCallback(this,function(response){  
       var state = response.getState();  
       if(state=='SUCCESS'){  
         var result = response.getReturnValue();  
         console.log('Result Returned: ' +result);  
         component.find("fileName").set("v.value", " ");  
         component.set("v.files",result);  
       }  
     });  
     $A.enqueueAction(action);  
   },  

 })

Here is the List view component:
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" controller="RelatedFilesController">
     
    <!--Attributes-->
    <aura:attribute name="cdList" type="List"/>
     
    <!--Handlers-->
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <aura:handler event="force:refreshView" action="{!c.doInit}" />
     
    <!--Component Start-->
    <table class="slds-table slds-table_cell-buffer slds-table_bordered">
        <thead>
            <tr class="slds-line-height_reset">
                <th class="slds-text-title_caps" scope="col">
                    <div class="slds-truncate" title="Title">Title</div>
                </th>
                <th class="slds-text-title_caps" scope="col">
                    <div class="slds-truncate" title="Created By">Created By</div>
                </th>
                <th class="slds-text-title_caps" scope="col">
                    <div class="slds-truncate" title="Created Date">Created Date</div>
                </th>
                <th class="slds-text-title_caps" scope="col">
                     
                </th>
            </tr>
        </thead>
        <tbody>
            <aura:iteration items="{!v.cdList}" var="cd">
                <tr>
                    <th scope="row">
                        <div class="slds-truncate" title="{!cd.Title}">
                            <a onclick="{!c.handleSelectedDocPreview}" data-Id="{!cd.Id}">{!cd.Title}</a>
                        </div>
                    </th>
                    <th scope="row">
                        <div class="slds-truncate" title="{!cd.CreatedBy.Name}">
                            <a onclick="{!c.handleRedirectToUserRecord}" data-Id="{!cd.CreatedById}">{!cd.CreatedBy.Name}</a>
                        </div>
                    </th>
                    <th scope="row">
                        <div class="slds-truncate" title="{!cd.CreatedDate}">
                            <lightning:formattedDateTime value="{!cd.CreatedDate}"/>
                        </div>
                    </th>
                    <th scope="row">
                        <lightning:buttonMenu alternativeText="Show menu" menuAlignment="auto" onselect="{!c.handleSelectedAction}" value="{!cd.Id}">
                            <lightning:menuItem value="Download" label="Download" iconName="utility:download" title="Download" />
                            <lightning:menuItem value="Delete" label="Delete" iconName="utility:delete" title="Delete"/>
                        </lightning:buttonMenu>
                    </th>
                </tr>  
            </aura:iteration>
        </tbody>
    </table>
    <!--Component End-->
</aura:component>

JS:
({
    //Get Related Docs
    doInit : function(component, event, helper) {
        helper.getRelatedDocuments(component, event); 
    },
     
    //Redirect To User Record
    handleRedirectToUserRecord: function (component, event, helper) {
        var recordId = event.currentTarget.getAttribute("data-Id")
        var navEvt = $A.get("e.force:navigateToSObject");
        navEvt.setParams({
            "recordId": recordId,
            "slideDevName": "Detail"
        });
        navEvt.fire();
    },
     
    //Preview Selected File
    handleSelectedDocPreview : function(component,event,helper){ 
        $A.get('e.lightning:openFiles').fire({
            recordIds: [event.currentTarget.getAttribute("data-Id")]
        });
    },
     
    //Handle Selected Action
    handleSelectedAction: function(component, event, helper) {
        var docId = event.getSource().get("v.value");
        var selectedMenuValue = event.detail.menuItem.get("v.value");
        switch(selectedMenuValue) {
            case "Delete":
                helper.deleteDocument(component, event, docId);
                break;
            case "Download":
                helper.downloadDocument(component, event, docId);
                break;
        }
    },
})

Helper:
({
    getRelatedDocuments : function(component, event) {
        var action = component.get("c.getRelatedDocs");
        action.setParams({
            recordId : component.get("v.recordId")
        });
        action.setCallback(this, function(response) {
            var state = response.getState();
            if(state === "SUCCESS"){
                component.set('v.cdList', response.getReturnValue());
            }else if(state === "INCOMPLETE") {
                console.log("INCOMPLETE");
            }else if(state === "ERROR"){
                var errors = response.getError();
                if(errors){
                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " +  errors[0].message);
                    }
                }else{
                    console.log("Unknown error");
                }
            }
        });
        $A.enqueueAction(action);  
    },
     
    deleteDocument : function(component, event, docId) {
        var action = component.get("c.deleteDoc");
        action.setParams({
            docId : docId
        });
        action.setCallback(this, function(response) {
            var state = response.getState();
            if(state === "SUCCESS"){
                this.getRelatedDocuments(component, event);
            }else if(state === "INCOMPLETE") {
                console.log("INCOMPLETE");
            }else if(state === "ERROR"){
                var errors = response.getError();
                if(errors){
                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " +  errors[0].message);
                    }
                }else{
                    console.log("Unknown error");
                }
            }
        });
        $A.enqueueAction(action);  
    },
     
    downloadDocument : function(component, event, docId) {
        var action = component.get("c.getDocURL");
        action.setParams({
            docId : docId
        });
        action.setCallback(this, function(response) {
            var state = response.getState();
            if(state === "SUCCESS"){
                var urlEvent = $A.get("e.force:navigateToURL");
                urlEvent.setParams({
                    "url": response.getReturnValue()
                });
                urlEvent.fire();
            }else if(state === "INCOMPLETE") {
                console.log("INCOMPLETE");
            }else if(state === "ERROR"){
                var errors = response.getError();
                if(errors){
                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " +  errors[0].message);
                    }
                }else{
                    console.log("Unknown error");
                }
            }
        });
        $A.enqueueAction(action);  
    }
})
SwethaSwetha (Salesforce Developers) 
HI Jon-Michael,
Based on your code, I see you implemented the file upload feature using lighting:fileUpload and the onuploadfinished. With onuploadfinished you could raise an event with every upload, so that your other component handles that and refreshes the data every time you upload a file.

Reference of this approach:https://salesforce.stackexchange.com/questions/231333/what-event-fire-when-you-attach-a-file-attachment-on-the-record-page

Also, see https://salesforce.stackexchange.com/questions/170542/automatically-refresh-lightning-component .

Hope this helps you. Please mark this answer as best so that others facing the same issue will find this information useful. Thank you