1

I have been asked this question by someone. I was not able to give a correct answer. Could you please help me out? Why we can't access the value of event (e) in setTimeout?

import React from 'react';
import { render } from 'react-dom';

class App extends React.Component{
  state = {
    number: 1,
  }

  handleNumber = (e) => {
    console.log(e)
    setTimeout(() => {
      console.log(e) // It becomes null here.
      if(e) {
      this.setState({number: this.state.number + 1})
      console.log(this.state.number)
    }
  }, 10)
  }

  render() {
    return (
      <div>
        <button onClick={this.handleNumber}>Hello world</button>
      </div>
)}
}

render(<App />, document.getElementById('root'));
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user10169731
  • 131
  • 11

1 Answers1

2

You should be able to access the event, more likely you're trying to access a property of the synthetic event like e.type or something like that. Because React reuses the synthetic event object, all properties of the event become null once the handleNumber function returns. See the docs for more info.

djfdev
  • 5,747
  • 3
  • 19
  • 38
  • I've taken another look on this question, after reading in the docs I realized you are correct in this case. But it seems that all the properties are null, isn't it because of the context? – Tomer Jun 03 '19 at 21:16
  • 1
    It's just how React handles events internally. When the event handler (`handleNumber`) returns, it mutates the event instance. So when the timeout fires, the properties are `null` instead of what they originally were. – djfdev Jun 03 '19 at 21:40
  • Thanks for the answer. I totally forgot to look into docs. Now it makes sense why I was not able to access event value in setTimeout. Thanks again. – user10169731 Jun 06 '19 at 06:32