0

I'm trying to enhance this already-working component, by replacing the Save button with Auto-save feature. I've simply moved onclick={saveCheckboxState()} from Save button to all lightning-input Checkboxes here.

Now, I need to prevent updateEventActivityCheckboxTracker() apex method from getting called too often.

You'll see I tried adding 3 second sleep here, but it's failing with 'sleep(3000)' isn't a recognized. Before I go down this road, please tell me...

Is there a much better way to do this with promises or similar? I'm too new to LWC and don't know where to start in this research.

  saveCheckboxState() {

    sleep(3000);

    this.activityIdsForTracker = [...this.template.querySelectorAll('lightning-input')]
                              .filter(element => element.checked)
                              .map(element => element.dataset.id);
    console.log('*** activityIdsForTracker: ' + this.activityIdsForTracker);

    updateEventActivityCheckboxTracker(
      {siteSurveyId:this.siteSurveyId,
       activityIdsForTracker:this.activityIdsForTracker, 
       status:'submitted:'});
  }

  sleep(milliseconds) {
    const date = Date.now();
    let currentDate = null;
    do {
      currentDate = Date.now();
    } while (currentDate - date < milliseconds);
  }
0

1 Answer 1

2

What you are trying to do is called debouncing. You want to use a combination of setTimeout() and clearTimeout() to keep extending the wait time until the user interaction stops long enough.

There is an example here in the @wire method documentation: https://developer.salesforce.com/docs/component-library/documentation/en/lwc/apex_wire_method

When a user clicks a checkbox, clear any existing timeout, then set a timeout to do your save. The one thing to be careful of is that you actually execute a save before the user navigates away. I would provide visual feedback when a save happens and would try making sure the save is executed in a disconnectCallback().

1
  • Thank you! I got pulled to another high priority task. I'll get back to this task soon, and try out as you recommend, and will report back. Aug 11, 2021 at 0:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .