Skip to content
Advertisement

Checking if a state object is empty

I have a react js state object and would like to execute some code if the object is empty. Is there something wrong with my logic because the code inside the if block is not getting executed.

if (this.state.errors == null) {
  this.props.updateUser(user);
  this.props.navigation.goBack();
}

Advertisement

Answer

Given that this.state.errors is an object you can do this,

//when this.state.errors object is empty 
if (Object.keys(this.state.errors).length == 0) {
  this.props.updateUser(user);
  this.props.navigation.goBack();
}

Object.keys will return an array or all the keys from the object this.state.errors. Then you can check the length of that array to determine if it is an empty object or not.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement