lightning-web-components – Why Can’t a While Loop Be Used in Export Default Class?

javascriptlightning-web-components

For some reason, I can't get this while-loop to work. The code in the export default class runs once, and I can never call back to it when variables are change from another LWC, and imported back to this file.

My code:

mapping.js

import { LightningElement, wire, api, track } from 'lwc';
import { MapMarkers } from './MapMarkers';
import { SearchString, SearchState, ClickCount } from 'c/mappingBox';

// Global Variables.
let SearchStreet = '1 abc street';
let SearchCity = 'Boston';

export default class Mapping extends LightningElement {

// Method should rerun updating when the button is clicked from the MappingBox.js file; (not working).
    SearchClick(event) {

        // The address entered into the search bar.
        const ArrStreet = SearchString.split(',');
        SearchStreet = ArrStreet[0];

        // The town or city entered into the search bar.
        const ArrCity = SearchString.split(',');
        SearchCity = ArrCity[1];

        // Updates and locates the location searched.
        this.mapMarkers = MapMarkers(SearchCity, SearchState, SearchStreet);

    }
        
    // What populates, before searching is done.
    mapMarkers = MapMarkers(SearchCity, SearchState, SearchStreet);

    // Not working?
    while( ClickCount = true ){

        this.SearchClick();
        ClickCount = false;

    }

}

mappingBox

 // Function when the search button is clicked.
    SearchClick(event) {

        SearchString = this.SearchText;
    
        ClickCount = true;

    }

More Detail:

"ClickCount" is then export to "mapping.js" file.

For some reason I can't get the method "SearchClick" from the "mapping.js" file to rerun, so the variable can update and output a different location on the mapping function.

Best Answer

You'll want to look at Communicate Across the DOM for details, but it appears that what you're looking for is a publisher-subscriber model. The documentation contains two examples, first using a generic pubsub library you can copy-paste into your project, the other using lightning-message-service. The general idea is the same for each; you subscribe to a message channel when the component loads, unsubscribe when a component unloads, and then you can publish when you want to fire off an event that subscribers will receive. You can still use your shared state variable, you'll just read the values when you get a message.

export default class MappingBox extends LightningComponent {
  connectedCallback() {
    subscribe('searchUpdated', this.#subscription);
  }
  disconnectedCallback() {
    unsubscribe('searchUpdated', this.#subscription);
  }
  // Note use of arrow function to bind to the class scope
  #subscription = (message) => {
    // Do something 
  }
Related Topic