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 {
...
if(!this.state.acessos.length) { ... }
setState
instead. The documentation states "Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable." Meaning you should avoid doing things likethis.state.acessos.push(...);
Technically what you're doing there works fine because you are usingsetState
after, but I wanted to point that out for anyone else happening across this.this.setState({ acessos: [...this.state.acessos, { uuid: ... }] })
would accomplish this. But as I mentioned, what you have works because you are callingthis.setState
after mutating it. I just wanted to make sure it was clear that mutating items in the state directly and not callingthis.setState
after would be problematic.