All notes >

The LWC Refactor That Broke event.target After await

A small cleanup refactor removed a local variable and introduced a subtle async bug in Lightning Web Components.


I hit a subtle async bug in LWC recently while doing what looked like a harmless refactor.

I removed an “unnecessary” local variable.

Then suddenly:

event.target.dataset.status

started returning undefined.

Before refactor

This worked perfectly:

async handleCustomButtonClick(event) {
    const newStatus = event.target.dataset.status;

    const result = await CustomModal.open();

    this.status = newStatus;
}

After refactor

I thought the variable was pointless and inlined it:

async handleCustomButtonClick(event) {
    const result = await CustomModal.open();

    this.status = event.target.dataset.status;
}

Now the status became undefined.

Why this happens

await pauses execution and resumes it later on the event loop.

By the time execution continues, the original event context is no longer guaranteed to exist.

So this:

event.target

may no longer be valid after the async boundary.

The original “unnecessary” variable was actually preserving the value before the pause.

Rule of thumb

If you need something from an event object later:

  • dataset
  • value
  • checked
  • id
  • target

extract it before await.

References