event data inside settimeout function is null in reactJs

Viewed 930

I have a react function

<button onClick={(e) => this.playVideo(e, name)}>

tried with both options

playVideo(event, name) {
    console.log(event, 'event details');
    setTimeout(function () {
      console.log(event, 'event details inside timeout'); 
    }, 1500)
}
playVideo(event, name) {
    console.log(event, 'event details');
    setTimeout(function (event) {
      console.log(event, 'event details inside timeout'); 
    }, 1500)
}

In the above code the initial event is working as expected but I need the event data inside settimout bcaz I have to load few js files based on the event, but event data inside settimeout function is always null.

I have also tried with onClickCapture but still no luck

<button onClickCapture={(e) => this.playVideo(e, name)}>
3 Answers

Prior to React-v17 you need the values to be in scope due to Syntethic Event wrapper used in React:

playVideo(event) => {
    const { currentTarget } = event;

    // closure on currentTarget won't lose due to synthetic event.
    setTimeout(() => {
      console.log(currentTarget, 'event details inside timeout'); 
    }, 1500)
}

You can pass parameter to setTimeout callback with additional parameters in setTimeout. Just add event object in parameter after }, 1500, event) and it will be available in callback.

playVideo(event, name) {
    console.log(event, 'event details');
    setTimeout(function (event) {
      console.log(event, 'event details inside timeout'); 
    }, 1500, event) // <- Pass event object from here
}

Edit As per the suggestion from @Felix King in comment you can use event object from parent scope playVideo with just remove parameter in callback like below.

playVideo(event, name) {
    console.log(event, 'event details');
    setTimeout(function () { // <- Do no add event parameter so event object will be fetch from parent scope.
      console.log(event, 'event details inside timeout'); 
    }, 1500)
}

Dont pass event parameter to settimeout function because it considered to be a local variable in this scope.

Related