Skip to main content

Communicate with Components Across an App

Update the Bear List Component

Park rangers have one last request for you. They would like to locate bears on a map as they filter the bear list. You have to create a bear map component and modify your bear list so that it sends events to the map. Let’s start by updating our bear list.

  1. Edit the bearList.js file.
  2. Add the following code before import { NavigationMixin } from 'lightning/navigation';:
    import { publish, MessageContext } from 'lightning/messageService';
    import BEAR_LIST_UPDATE_MESSAGE from '@salesforce/messageChannel/BearListUpdate__c';
    The first import brings utilities from the Lightning Messaging Service (LMS). This service lets you publish messages across sibling components in a Lightning page over a Lightning message channel.
    The second import is Lightning message channel that was included in the base project that you retrieved from GitHub.
  3. Replace these two lines...
    @wire(searchBears, {searchTerm: '$searchTerm'})
    bears;
    ...with the following code:
    bears;
    @wire(MessageContext) messageContext;
    @wire(searchBears, {searchTerm: '$searchTerm'})
    loadBears(result) {
      this.bears = result;
      if (result.data) {
        const message = {
          bears: result.data
        };
        publish(this.messageContext, BEAR_LIST_UPDATE_MESSAGE, message);
      }
    }
    Code highlights:
    • We retrieve the Lightning message context and store it in a messageContext property.
    • We use a wired function to capture incoming bear list data and fire a custom BearListUpdate__c Lightning message with the list of bear records.
    • We pass searchTerm as a dynamic parameter to our wired searchBears adapter so that each time searchTerm changes, loadBears is re-executed and we fire a new message with the new search results.
    • We use the publish function that we imported from LMS to fire a BearListUpdate__c Lightning message with the bear list.

Create the Bear Map Component

  1. In VS Code, right-click the lwc folder and click SFDX: Create Lightning Web Component.
  2. Name the component bearMap.
  3. Edit the bearMap.js-meta.xml file, and replace <isExposed>false</isExposed> with these lines.
    <isExposed>true</isExposed>
    <targets>
    	<target>lightning__AppPage</target>
    	<target>lightning__RecordPage</target>
    	<target>lightning__HomePage</target>
    </targets>
    This enables your component to be placed on any type of page.
  4. Replace the contents of bearMap.html with:
    <template>
    	<article class="slds-card">
    		<lightning-map
    			map-markers={mapMarkers}
    			zoom-level="11"
    			markers-title="Bears">
    		</lightning-map>
    	</article>
    </template>
    Code highlights:
    • We display a card component that contains a map.
    • The map displays items from a mapMarkers array.
  5. Replace the contents of bearMap.js with:
    import { LightningElement, wire } from 'lwc';
    import { subscribe, unsubscribe, MessageContext } from 'lightning/messageService';
    import BEAR_LIST_UPDATE_MESSAGE from '@salesforce/messageChannel/BearListUpdate__c';
    export default class BearMap extends LightningElement {
      mapMarkers = [];
      subscription = null;
      @wire(MessageContext)
      messageContext;
      connectedCallback() {
        // Subscribe to BearListUpdate__c message
        this.subscription = subscribe(
            this.messageContext,
            BEAR_LIST_UPDATE_MESSAGE,
            (message) => {
                this.handleBearListUpdate(message);
            });
      }
      disconnectedCallback() {
        // Unsubscribe from BearListUpdate__c message
        unsubscribe(this.subscription);
        this.subscription = null;
      }
      handleBearListUpdate(message) {
        this.mapMarkers = message.bears.map(bear => {
          const Latitude = bear.Location__Latitude__s;
          const Longitude = bear.Location__Longitude__s;
          return {
            location: { Latitude, Longitude },
            title: bear.Name,
            description: `Coords: ${Latitude}, ${Longitude}`,
            icon: 'utility:animal_and_nature'
          };
        });
      }
    }
    Code highlights:
    • We implemented two component lifecycle hook functions: connectedCallback and disconnectedCallback. These are automatically called when the component loads and unloads. We use these two functions to subscribe and unsubscribe from our custom BearListUpdate__c Lightning message.
    • As soon as we receive a BearListUpdate__c message, the handleBearListUpdate function gets called with the list of bear records that are currently filtered. handleBearListUpdate builds a list of map markers that are passed to the mapMarkers property and then displayed on our map component.
  6. Deploy the updated code to the org. Right-click the default folder and click SFDX: Deploy Source to Org.

Add the Bear Map Component to the App Home Page

Let’s add our new component to the app home page.

  1. Back in your org, from the App Launcher ( App Launcher), find and select Ursus Park.
  2. Click Setup ( Setup Gear) and select Edit Page.
  3. Under Custom Components, find your bearMap component and drag it to the top right of the page.
  4. Click Save and Back to return to the home page and check that the map updates itself when you filter the bear list.

Bear map showing filtered bear records

Project Summary

That’s a wrap. Park rangers can now easily track bears thanks to your efforts.

You’ve used all of the core concepts of Lightning Web Components throughout this project: data binding, expressions, conditional rendering, imperative and wired Apex, component composition, and inter-component events.

Make the best use of this knowledge by building your own flexible apps with Lightning Web Components. Happy coding!

Comparta sus comentarios sobre Trailhead en la Ayuda de Salesforce.

Nos encantaría conocer su experiencia con Trailhead. Ahora puede acceder al nuevo formulario de comentarios cuando quiera desde el sitio de la Ayuda de Salesforce.

Más información Continuar para compartir comentarios