Proz1g
Proz1g

Reputation: 1227

Check if an array is empty in React Native

How can I check if an array is empty with a IF statment?

I have this array 'acessos' that's empty

...
constructor(props){
    super(props);
    this.state = {
      acessos:[]
    };
  }
...

Then I'm trying to check if 'acessos' is empty and if it is I push some data in it. I've tried with null but with no results, so how can I check if is empty?

...
if(this.state.acessos === null){
      this.state.acessos.push({'uuid': beacons.uuid, 'date':date});
      this.setState({acessos: this.state.acessos});
} else {
...

Upvotes: 32

Views: 183699

Answers (6)

Ihsanu Rahman
Ihsanu Rahman

Reputation: 15

 Array?console.log('array is empty'):console.log('array have values')

or

if (Array){
   console.log('array is empty')
else{
   console.log('array have values')
}

Upvotes: 0

sahba
sahba

Reputation: 39

instead ofnull its better to replace "" like this if ( this.state.acessos == ""){}

Upvotes: 0

N Kurt
N Kurt

Reputation: 154

If checking the array length as part of conditional rendering in React JSX, remember that if condition is falsy at length check, it will render a 0 as in the following example:

{myArray && myArray.length && (
      <div className="myclass">
        Hello
      </div>
    )}

This is not what we want most of the time. Instead you can modify the JSX as follows:

{myArray && myArray.length? (
      <div className="myclass">
        Hello
      </div>
    ):""}

Upvotes: 7

oma
oma

Reputation: 1894

Just check if your array exists and has a length:

if (this.state.products && this.state.products.length) {
     //your code here
}

No need to check this.state.products.length > 0.
0 is falsy anyway, a small performance improvement.

Upvotes: 32

Philip John
Philip John

Reputation: 5565

You need not even check for the length since ECMAScript 5.1 You can simply write the same condition as follows.

this.state.acessos && this.state.acessos.length

By default this.state.acessos.length checks if the length is NOT undefined or null or zero.

Upvotes: 6

atitpatel
atitpatel

Reputation: 3184

I agree to Julien. Also you don't have to compare it to null. You can write it like

this.state.acessos && this.state.acessos.length > 0

Upvotes: 53

Related Questions