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

JavascriptReactjs

Javascript Problem Overview


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=> ...)?

Javascript Solutions


Solution 1 - Javascript

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>

Solution 2 - Javascript

With the comment from @thirtydot I got a working solution.

>I think it's because setState is "async", so by the time the function you pass to setState is executed (and the event is accessed), the event is no longer around. In the second version, the event is accessed immediately and its currentTarget passed to setState

So I stored the event.currentTarget to a variable and used that as it's explained in the ReactJs Event Pooling

Looks like this and it works

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

However this does not explain why event.persist() is not working. I'll accept the answer which explains it.

Solution 3 - Javascript

To resolve this issue - before calling handleSubmit of form, call event.persist() and then in handleSubmit() definition - write your logic. For e.g.

<form id="add_exp_form" onSubmit={(event) => {event.persist();this.handleSubmit(event)}}>
             
handleSubmit(event){
    // use event.currentTarget - It will be visible here
}

Solution 4 - Javascript

In your function you should use const event.preventDefault() or event.prevent()

example:

updateSpecs1 = (event) => { 
    event.preventDefault()

Solution 5 - Javascript

I came across similar warning message when filling components dynamically and to solve this I just had to wrap function with arrow function.

From:

{ text: "Delete item", onClick: deleteItem },

To:

{ text: "Delete item", onClick: (id) => deleteItem(id) },

Solution 6 - Javascript

There is a nice description about this problem and 2 different solution, you can check with this link

Solution 7 - Javascript

You can handle it using curried function like this.

const persistEvent = (fun: any) => (e: any) => {
e.persist();
fun(e);
};

now you can write your function like

persistEvent(toggleFilter);

It's going to be something like this:

const persistEvent = (fun: any) => (e: any) => {
    e.persist();
    fun(e);
    };

const delayedFunctionality = (e) => {
  setTimeout(()=> {
     console.log(e.target.value)
  },500
}

<input onChange={persistEvent(delayedFunctionality)} />

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMurat Karag&#246;zView Question on Stackoverflow
Solution 1 - JavascriptLyubomirView Answer on Stackoverflow
Solution 2 - JavascriptMurat KaragözView Answer on Stackoverflow
Solution 3 - JavascriptRuchi WadhwaView Answer on Stackoverflow
Solution 4 - Javascriptuser7396942View Answer on Stackoverflow
Solution 5 - JavascriptKunokView Answer on Stackoverflow
Solution 6 - JavascriptEsin ÖNERView Answer on Stackoverflow
Solution 7 - JavascriptAmir GorjiView Answer on Stackoverflow