Rachit Gupta
Rachit Gupta

Reputation: 89

How to call 2 functions after the setState is called in React?

I have to call 2 functions just after the setState is updated. I want to use callback Function. But the problem is one function is present in the current component and the other function I am calling of the child component(using refs). The code looks something like this:

  handleChange_First = (event) => {
    

    const name = event.target.name;
   
    this.setState({
        [name]: event.target.value
    },() => {this.calculate()});
    this.child.handleChange(event)
   }

I want to call this.calculate() and this.child.handleChange(event), as soon as the setState is changed. Right now it is updating the value of the current component (this.calculate) but the value of the child component (handleChange) is not updating.

Or if there is any alternative way to call both the functions simultaneously just after the setState, that will also be very helpful.

Upvotes: 1

Views: 280

Answers (3)

Abdellah Sabiri
Abdellah Sabiri

Reputation: 396

You might try to call by a setTimeout, which will execute the function independently.

handleChange_First = (event) => {

    const name = event.target.name;

    this.setState({
        [name]: event.target.value
    },() => {this.calculate()});

    setTimeOut(()=>{
      this.child.handleChange(event);
    })
   }

Upvotes: 0

Agney
Agney

Reputation: 19194

React uses a synthetic event pattern. From the docs:

The SyntheticEvent is pooled. This means that the SyntheticEvent object will be reused and all properties will be nullified after the event callback has been invoked. This is for performance reasons. As such, you cannot access the event in an asynchronous way.

This is the same reason, you are not able to use event in the callback. (setState is async, the reason you had to use callback in the first place)

There is an escape hatch though, you can ask React not to pool the event by calling event.persist()

handleChange_First = (event) => {
  event.persist();
  const name = event.target.name;

  this.setState({[name]: event.target.value},() => {
     this.calculate();
     this.child.handleChange(event);
  });
}

Upvotes: 2

Naor Levi
Naor Levi

Reputation: 1813

Enter the second function call into the callback function body. Try this:

handleChange_First = (event) => {
        const name = event.target.name;

        this.setState({[name]: event.target.value},() => {
                this.calculate();
                this.child.handleChange(event);
              });
}

Upvotes: 2

Related Questions