Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS can't set state from an event with event.persist()

I need to set a state field which I get from an event, but it doesn't get set when I pass a function to it. The component and method looks like the following:

constructor(props: SomeProps, context: any) {   super(props, context);   this.state = {     isFiltering: props.isFiltering,     anchor: "",   }; }  private toggleFilter = (event: any) => {   event.persist()   this.setState(prevState => ({     isFiltering: !prevState.isFiltering,     anchor: event.currentTarget // does not work, it's null   })); } 

If I remove event.persist() then I get the following error :

This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the method currentTarget on a released/nullified synthetic event. This is a no-op function. If you must keep the original synthetic event around, use event.persist(). See https://facebook.github.io/react/docs/events.html#event-pooling for more information.

For some reason the following code works:

private toggleFilter = (event: any) => {   this.setState({anchor:event.currentTarget}) // works fine   this.setState(prevState => ({     isFiltering: !prevState.isFiltering,   })); } 

Why does the above works but not when I use this.setState(prevState=> ...)?

like image 825
Murat Karagöz Avatar asked Feb 07 '17 12:02

Murat Karagöz


People also ask

What is event persist () React?

persist() . React uses the SyntheticEvent objects to wrap native events. For performance reasons, synthetic events are pooled and reused across multiple native events. To assure consistent usage of the pooled events, React nullifies the properties of synthetic events right after executing an event handler.

Why isn't my state updating React?

The reason why the state doesn't update immediately is because for each render, the state is immutable. …are both constants values ! So they're immutable. The state remains constant inside the render but can be changed between two renders.

How do you set state in React?

State can be updated in response to event handlers, server responses, or prop changes. This is done using the setState() method. The setState() method enqueues all of the updates made to the component state and instructs React to re-render the component and its children with the updated state.

How do you use event stopPropagation in React?

event.stopPropagation() This will stop any parent component's event from firing. To use this: Make sure to pass the event object as a parameter. Use the stopPropagation method on the event object above your code within your event handler function.


1 Answers

That's the expected behaviour, because event.persist() doesn't imply that currentTarget is not being nullified, in fact it should be - that's compliant with browser's native implementation.

This means that if you want to access currentTarget in async way, you need to cache it in a variable as you did in your answer.


To cite one of the React core developers - Sophie Alpert.

currentTarget changes as the event bubbles up – if you had a event handler on the element receiving the event and others on its ancestors, they'd see different values for currentTarget. IIRC nulling it out is consistent with what happens on native events; if not, let me know and we'll reconsider our behavior here.

Check out the source of the discussion in the official React repository and the following snippet provided by Sophie that I've touched a bit.

var savedEvent;  var savedTarget;    divb.addEventListener('click', function(e) {    savedEvent = e;    savedTarget = e.currentTarget;    setTimeout(function() {      console.log('b: currentTarget is now ' + e.currentTarget);    }, 0);  }, false);    diva.addEventListener('click', function(e) {    console.log('same event object? ' + (e === savedEvent));    console.log('same target? ' + (savedTarget === e.currentTarget));    setTimeout(function() {      console.log('a: currentTarget is now ' + e.currentTarget);    }, 0);  }, false);
div {    padding: 50px;    background: rgba(0,0,0,0.5);    color: white;  }
<!DOCTYPE html>  <html>  <head>    <meta charset="utf-8">    <title>JS Bin</title>  </head>  <body>      <div id="diva"><div id="divb"> Click me and see output! </div></div>      </body>  </html>
like image 66
Lyubomir Avatar answered Oct 06 '22 04:10

Lyubomir