Home > OS >  Why console.log not return the value 1?
Why console.log not return the value 1?

Time:06-28

From my database I have set one person to be "banned" but instead of printing the value "1" it leaves it empty and even when the value is 0 it still leaves it empty.

 for (const dataItem of res.data.data) {

  var IsBanned = 0 ;
  if(dataItem.banned === true){ 
  this.setState({IsBanned: this.state.count  1})
  console.log("Local", IsBanned);
  } 
}

console.log

any advice is appreciated

CodePudding user response:

this.setState() is async function so it does take some time to update value in state.

You can utilise 2nd argument of setState which is callback

this.setState({IsBanned: this.state.count  1},()=>console.log("Local", this.state.IsBanned);)

Here you have taken isBanned as local variable, but trying to update it as state variable. So you first need to decide whether to keep it in state or in local.

CodePudding user response:

1.This code may fail to update the counter:

this.setState({IsBanned: this.state.count  1})
console.log("Local", IsBanned);

2.You have to use this because setState() that accepts a function rather than an object.

this.setState((state) => ({IsBanned: state.counter   1}));
  • Related