user2477504
user2477504

Reputation: 73

ReactJs setState callback not working

I have a strange behavior with the setState callback, hopefully somebody can help. The callback just isn't fired.

Here is what I do:

this.setState(
  (prevState, props) => {
    return { first: obj, questions: [] }
  },
  this.changeStateCb
);

For some reason the changeStateCb function is never being called. Same problem when I change it to:

this.setState(
  (prevState, props) => {
    return { first: obj, questions: [] }
  },
  () => console.log(this.state)
);

I just updated from v15.x to 16.2.0

Upvotes: 3

Views: 3429

Answers (3)

Moonwalker
Moonwalker

Reputation: 3802

Have the same issue. The callback is not invoked. I traced it to React min code and the function to enqueueSetState does not accept the callback even though it is passed in from internal React code...so code explains why it is not called. But this used to work just fine in React 15.x - what's going on...I am trying React 16.8.4

Upvotes: 0

LukeP
LukeP

Reputation: 1605

I just had the same issue happen to me. A simple console.log('test') in the callback wouldn't even run. It turns out I had to delete my /dist folder in the build directory. I am using Type Script and webpack and upgraded from a .net core template.

Upvotes: 1

Alex
Alex

Reputation: 3855

Do you have a demo? I just put up a simple working example, and it seems to run just fine under React 16.2.0. Do note though that the optional callback should be used sparingly. As the docs mention, it will be executed once setState is completed and the component is re-rendered. So, a better place to do the logic in this.changeStateCb would be inside componentDidUpdate.

Upvotes: 1

Related Questions