Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an array is empty in React Native

Tags:

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 { ... 
like image 716
Proz1g Avatar asked May 09 '17 11:05

Proz1g


People also ask

How do you check if array is empty React Native?

To check if an array is empty in React, access its length property, e.g. arr. length . If an array's length is equal to 0 , then it is empty. If the array's length is greater than 0 , it isn't empty.

How do I check if an array is empty?

To check if an array is empty or not, you can use the . length property. The length property sets or returns the number of elements in an array. By knowing the number of elements in the array, you can tell if it is empty or not.


2 Answers

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 
like image 111
atitpatel Avatar answered Sep 18 '22 01:09

atitpatel


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.

like image 43
oma Avatar answered Sep 18 '22 01:09

oma