0

I have a strange question about set state's callback function in React. Everything is working fine in React 15 but once I upgraded the react version to 16, the set state's callback function is not getting fired. I have tried almost everything but I could not clearly find out what makes this issue.

I have tried binding the function in the constructor, using an anonymous function inside the set state method but none of them actually worked.

Then I tried downgrading the react version back to 15 and ran the project and I was able to fire the callback method (tested by putting an alert box inside the callback function).

Here's the exact code that i'm using in my sample project:

This function is called on a button click

incrementCounter() {
    this.setState({
        currentCount: this.state.currentCount + 1
    }, this.callbackfuncsajad.bind(this));
}

This is the set state's callback function

callbackfuncsajad = () => {
    alert('in the callback');
}

This is my package.json to check if there's any version mismatch:

  • "react": "^15.6.2"
  • "react-dom": "^16.6.3"
  • "@types/react": "^15.0.35"
  • "@types/react-dom": "^15.5.8"
  • "typescript": "2.4.1"

As a side note: I am using Visual Studio 2017 ASP.NET's default React.JS template for my project. The project comes by default with React 15 along with typescript.

Would be a big time help if anyone could figure this issue out.

Thanks.

Sajad Jaward
  • 247
  • 5
  • 16
  • 1
    can u try binding that function to this in constructor and just pass it as callback – Leela Venkatesh K Nov 23 '18 at 09:25
  • Please, provide https://stackoverflow.com/help/mcve . It's unknown how incrementCounter is used. `this` could be already wrong there. – Estus Flask Nov 23 '18 at 09:27
  • There is a mismatch between the `react` and `react-dom`'s version. Please keep the version of both `react` and `react-dom` same. If you want to use the latest version of react then keep `"react": "16.6.3"` and `"react-dom": "16.6.3"` – Hardik Modha Nov 23 '18 at 09:30
  • 1
    @klvenky The callback is an arrow function so no need to `bind`. – Hardik Modha Nov 23 '18 at 09:34

1 Answers1

1

Hi I think its due to parent context, so try somthing like this.

incrementCounter() {
this.setState({
    currentCount: this.state.currentCount + 1
}, () => { this.callbackfuncsajad() });

}

Hope it helps. If you still face this problem kindly share code for proper deduction.

kshitij
  • 642
  • 9
  • 17