Setstate Doesn't Update the State Immediately

setState doesn't update the state immediately

This callback is really messy. Just use async await instead:

async openAddBoardModal(){
await this.setState({ boardAddModalShow: true });
console.log(this.state.boardAddModalShow);
}

React setState not Updating Immediately

You should invoke your second function as a callback to setState, as setState happens asynchronously. Something like:

this.setState({pencil:!this.state.pencil}, myFunction)

However in your case since you want that function called with a parameter you're going to have to get a bit more creative, and perhaps create your own function that calls the function in the props:

myFunction = () => {
this.props.updateItem(this.state)
}

Combine those together and it should work.

React setState not updating state

setState() is usually asynchronous, which means that at the time you console.log the state, it's not updated yet. Try putting the log in the callback of the setState() method. It is executed after the state change is complete:

this.setState({ dealersOverallTotal: total }, () => {
console.log(this.state.dealersOverallTotal, 'dealersOverallTotal1');
});

setState doesn't update state in react

You don't need refresh state

Highlights:
Add the response in state and use state to render cards

Try below code:

state = {
reminders: []
}

fetch('http://localhost:5000/addrem',{
method: 'POST',
headers:{'Content-Type': 'application/json'},
body: JSONdata,
}).then(resp => resp.json().then(data =>{
if (data){
this.response = data
this.setState({
reminders: this.response.reminders
})
}
}))

{
this.state.reminders.map((item,i=0) =>{
return <Card key={i++} reminder={item}/>
})
}

P.S - Don't use map iteration(i) as the key, use attribute from the reminders array that uniquely identifies the card.

Why calling setState method doesn't mutate the state immediately?

Reason is setState is asynchronous, you can't expect the updated state value just after the setState, if you want to check the value use a callback method. Pass a method as callback that will be get executed after the setState complete its task.

Why setState is asynchronous ?

This is because setState alters the state and causes re rendering. This can be an expensive operation and making it synchronous might leave the browser unresponsive.
Thus the setState calls are asynchronous as well as batched for better UI experience and performance.

From Doc:

setState() does not immediately mutate this.state but creates a
pending state transition. Accessing this.state after calling this
method can potentially return the existing value. There is no
guarantee of synchronous operation of calls to setState and calls may
be batched for performance gains.

Using callback method with setState:

To check the updated state value just after the setState, use a callback method like this:

setState({ key: value }, () => {
console.log('updated state value', this.state.key)
})

Check this:

class NightlifeTypes extends React.Component {

constructor(props) {

super(props);

this.state = {

barClubLounge: false,

seeTheTown: true,

eventsEntertainment: true,

familyFriendlyOnly: false

}

}

handleOnChange = (event) => { // Arrow function binds `this`

let value = event.target.checked;

if(event.target.className == "barClubLounge") {

this.setState({ barClubLounge: value}, () => { //here

console.log(value);

console.log(this.state.barClubLounge);

//both will print same value

});

}

}

render() {

return (

<input className="barClubLounge" type='checkbox' onChange={this.handleOnChange} checked={this.state.barClubLounge}/>

)

}

}

ReactDOM.render(<NightlifeTypes/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/>

Why does calling react setState method not mutate the state immediately?

From React's documentation:

setState() does not immediately mutate this.state but creates a
pending state transition. Accessing this.state after calling this
method can potentially return the existing value. There is no
guarantee of synchronous operation of calls to setState and calls may
be batched for performance gains.

If you want a function to be executed after the state change occurs, pass it in as a callback.

this.setState({value: event.target.value}, function () {
console.log(this.state.value);
});

React useState not updating on first click

as state updates are async, you may see your state value updating by adding building to a useEffect dependency, thus causing it to fire whenever the value of building changes.

const [building, setBuilding] = useState(0);

useEffect(() => {
console.log(building);
}, [building]);

return (
<button
title="tester"
onClick={() => {
setBuilding(1);
}}
>
test
</button>
);


Related Topics



Leave a reply



Submit