[TIL] Javascrip Dev 1 - Summer '23 Review Notes

Synchronizing component data without a page refresh using RefreshView API

lightning/refresh module and RefreshView API provides a way to refresh component data in LWC. Updates the data for a specific hierarchy of components. Can refresh data for Salesforce Platform containers, LWC and Aura.

Querying DOM elements with refs

Refs can be used to access elements in shadow DOM and light DOM. Refs locate DOM elements without a selector and only query elements contained inside the template. Previously, we could only use the querySelector() to locate specific DOM elements.

  1. Add the lwc:ref and assign it a value.

  2. Call this using this.refs

<template>
    <div lwc:ref="myDiv"></div>
</template>
export default class extends LightningElement {
  renderedCallback() {
    console.log(this.refs.myDiv);
  }
}

Using this.refs for a nonexistent ref, returns undefined. If duplicates are available, this.refs references the last directive. For a component with more than one template this.refs refers to the most recently rendered template.

Overlays with the new modal component

To create a modal component, import LightningModal from lightning/modal in your JavaScript file. Then, create a component class that extends LightningModal.

/* c/myModal.js */
import { api } from 'lwc';
import LightningModal from 'lightning/modal';
export default class MyModal extends LightningModal {
    handleOkay() {
        this.close('okay');
   }
}

This component doesn’t use a lightning-modal tag. Instead, the modal’s HTML template uses helper lightning-modal-* components to make the modal’s header, footer, and body. The lightning-modal-body component is required, and the others are optional.

<!-- c/myModal.html -->
<template>
    <lightning-modal-header label="My Modal Heading"></lightning-modal-header>
 <lightning-modal-body>This is the modal’s contents.</lightning-modal-body>
  <lightning-modal-footer>
      <lightning-button label="OK" onclick={handleOkay}></lightning-button>
  </lightning-modal-footer>
</template>