Nithin Srinivasan
Nithin Srinivasan

Reputation: 515

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();
}

Upvotes: 23

Views: 126171

Answers (5)

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

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.

Upvotes: 56

Mbanda
Mbanda

Reputation: 1018

-- if is Array

if(!this.state?.example?.length)  //ES 6 and above

-- if is Object

if(!Object.entries(this.state?.example).length)

Upvotes: -1

charul Tiwari
charul Tiwari

Reputation: 31

Actually, You need to first check this.state.errors is exist or not and then for object is null or not

if (this.state.errors && !Object.keys(this.state.errors)) {
    this.props.updateUser(user);
    this.props.navigation.goBack();
}

Upvotes: 2

Vignesh Raja
Vignesh Raja

Reputation: 8751

You may need to do like this.

if (this.state && !this.state.errors) {
  this.props.updateUser(user);
  this.props.navigation.goBack();
}

When you are accessing the values of object within another object, you might wanna check if the parent object present. If the object this.state is null or undefined, it just throws a console error.

Uncaught TypeError: Cannot read property 'errors' of undefined
at <anonymous>:1:15

Upvotes: 1

iHazCode
iHazCode

Reputation: 771

Try checking the state instead of the errors collection:

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

cheers

Upvotes: 1

Related Questions