What is the best way to show a loading indicator or spinner while retrieving data from Apex in a Lightning Web Component?

LWC Spinner


What is the best way to show a loading indicator while retrieving data from Apex in a Lightning Web Component?



The best way to show a loading indicator in a Lightning Web Component while retrieving data from Apex is to use a combination of HTML, CSS, and JavaScript. Here is an example of how to do it:

HTML:


<template>
  <div class="loading-container" if:true={isLoading}>
    <lightning-spinner alternative-text="Loading"></lightning-spinner>
  </div>
  <template if:false={isLoading}>
    <!-- Render the data here -->
  </template>
</template>

CSS:


.loading-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 50vh;
  }

JavaScript:


import { LightningElement, track } from 'lwc';
import { loadData } from './dataService';

export default class MyComponent extends LightningElement {
  @track isLoading = false;

  connectedCallback() {
    this.isLoading = true;
    loadData()
      .then(data => {
        // process the data here
        this.isLoading = false;
      })
      .catch(error => {
        // handle the error here
        this.isLoading = false;
      });
  }
}

In the above example, the isLoading property is used to toggle the visibility of the loading spinner and the data. The loadData method represents a hypothetical function that retrieves data from Apex. When the component is first connected to the DOM, the connectedCallback method is called, and the isLoading property is set to true, which causes the spinner to be displayed. Once the data is retrieved, the isLoading property is set back to false, which causes the spinner to be hidden and the data to be displayed.

Post a Comment

0 Comments