💼 This rule is enabled in the 🔍 browser config.
Accessing event.currentTarget inside an async function() will likely be null as currentTarget is mutated as the event is propagated.
- A
clickevent is dispatched - The handler is invoked once with the expected
currentTarget - An
awaitdefers the execution - The event dispatch continues,
event.currentTargetis modified to point to the current target of another event handler and nulled out at the end of the dispatch - The async function resumes
event.currentTargetis nownull
If you're using async, you'll need to synchronously create a reference to currentTarget before any async activity.
👎 Examples of incorrect code for this rule:
document.addEventListener('click', async function (event) {
// event.currentTarget will be an HTMLElement
const url = event.currentTarget.getAttribute('data-url')
const data = await fetch(url)
// But now, event.currentTarget will be null
const text = event.currentTarget.getAttribute('data-text')
// ...
})👍 Examples of correct code for this rule:
document.addEventListener('click', function (event) {
const currentTarget = event.currentTarget
const url = currentTarget.getAttribute('data-url')
// call async IIFE
;(async function () {
const data = await fetch(url)
const text = currentTarget.getAttribute('data-text')
// ...
})()
})Alternatively, extract a function to create an element reference.
document.addEventListener('click', function (event) {
fetchData(event.currentTarget)
})
async function fetchData(el) {
const url = el.getAttribute('data-url')
const data = await fetch(url)
const text = el.getAttribute('data-text')
// ...
}4.3.2