setstate is not working properly in react-native
You're using console.log
right after setState
, above results are expected because setState
is asynchronous. So console.log
is executed with old state instead of new state (new state has not been assigned yet).
You need to use the callback form of setState
to get the right state.
this.setState({ size: 'L' }, (state) => console.log("Button id:", id ,"size :",state.size))
You can read more about it here: https://reactjs.org/docs/react-component.html#setstate
// Added (I don't have enough rep to comment)
I saw John Lim's answer that suggests to use await
, but setState
does not return a Promise
, so await
won't work here. https://github.com/facebook/react/blob/0e100ed00fb52cfd107db1d1081ef18fe4b9167f/packages/react/src/ReactBaseClasses.js#L57-L66