Site icon Salesforce Diaries

Force Refresh View in LWC

Refresh View was must needed feature missing in Lightning Web Component. When a change is invoked from custom LWC, user had to refresh the page manually by reloading it. Good news is refreshview module is now available to use directly in LWC. The new lightning/refresh module and RefreshView API provide a standard way to refresh component data in Lightning web components (LWC) and Aura components.

force refresh view use case in Lightning Web Component

Business asked you to add a custom file uploader on account record page. They also expect the files uploaded should be available in notes and attachment related list without refreshing the page by reloading.

Code – force refresh view for file uploader

Let’s create a Lightning Web Component with name fileUploader. We will use standard base component for file upload by passing the current record id in it.

fileUploader.html

<template>
    <lightning-file-upload
        label="Attach receipt"
        name="fileUploader"
        accept={acceptedFormats}
        record-id={recordId}
        onuploadfinished={handleUploadFinished}
        multiple
    >
    </lightning-file-upload>
</template>

fileUploader.js

RefreshEvent signals other standard component to refresh when fired. We are firing it after file upload is done.

import { LightningElement, api } from 'lwc';
import { RefreshEvent } from 'lightning/refresh';
export default class FileUploader extends LightningElement {
    @api recordId;

    get acceptedFormats() {
        return ['.pdf', '.png'];
    }

    handleUploadFinished(event) {
        // refresh the standard related list
        this.dispatchEvent(new RefreshEvent());
    }
}

fileUploader.js-meta.xml

We can place the component on record page based on targets added in xml. We can modify it based on business requirement.

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>57.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

Demo – Refresh View API in LWC

Do you need help?

Stuck while working on this requirement? Do you want to get review of your solution? Now, you can book dedicated 1:1 with me on Lightning Web Component completely free.

GET IN TOUCH

Schedule a 1:1 Meeting with me

Also check out https://salesforcediaries.com/category/lightning-web-com

Exit mobile version