Reputation: 357
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:
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.
Upvotes: 0
Views: 147
Reputation: 710
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.
Upvotes: 1