Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 667
user2477504 Avatar asked Jul 01 '26 08:07

user2477504


2 Answers

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.

like image 166
Alex Avatar answered Jul 03 '26 20:07

Alex


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.

like image 31
LukeP Avatar answered Jul 03 '26 20:07

LukeP