Lightning Web Components – Refresh LWC Without Button Click or Page Reload When Different Record is Updated

apexlightning-web-componentslwc-wire-adapterrefreshapex

I have the following lwc, myComponent that will query related objects and display some fields when someone visits the record page of the Account record. I want to refresh the data without the click of a button or page reloading as soon as the related object is updated.

Question

  1. How can I refresh the data from a lightning record page when a related object is updated without a button click or page reload?

current code

myComponent.js

import { LightningElement, wire, api, track } from 'lwc';
import getRecordsMethod from '@salesforce/apex/MyController.getRecords';

export default class MyComponent extends NavigationMixin(LightningElement) {
  @api myRecord;

  @wire(getRecordsMethod)
  wiredRecord({ error, data }) {
    if(error) { // error code }
    else if(data) { this.myRecord = data; }

   /** how do we refresh this.myRecord? **/
  }
  handleOnClick(event) {
    /* refreshApex(this.wiredRecord); */

    /* this also didn't work */
    // refreshApex(this.myRecord);
  }
}

MyController.getRecords

@AuraEnabled(cacheable=true)
public static List<Account> getRecords() {
  return [SELECT Id, Name,
                 (SELECT Id, Name, MyField_to_Update__c
                  FROM Opportunities),
                 (SELECT Id, Name, Field_updated__c
                  FROM Contacts)
          From Account
          LIMIT 10];
}

MyComponent.hmtl

<template>
  <template if:true={wiredRecord.data}>
        <template for:each={wiredRecord.data} for:item="accnt" for:index="idx">
            <div key={accnt.Id} class="slds-m-bottom_medium">
                <p>{accnt.Name}</p>
                <p>{accnt.MyField_to_Update__c}</p> 
            </div>
        </template>
        <!-- Click the button to render -->
        <lightning-button label="rerender" onclick={handleOnClick}></lightning-button>
    </template>
</template>

Best Answer

You just need to make your component context-aware:

export default class MyComponent extends NavigationMixin(LightningElement) {
  @api recordId; // Provided by the runtime
  @wire(getRecordsMethod, { accountId: '$recordId' }) account; // reactive

And in your Apex, just pass in the record Id:

@AuraEnabled(cacheable=true)
public static List<Account> getRecords(Id recordId) {
  return [SELECT Id, Name,
           (SELECT Id, Name, MyField_to_Update__c
             FROM Opportunities),
           (SELECT Id, Name, Field_updated__c
             FROM Contacts)
          From Account WHERE Id = :recordId];
}
Related Topic