0

I'm passing an array from an API and want to know if the array is empty, to print an error message.

Look at different sites and none of them were working.

      {this.props.items ? errorMessage : <h1>Working</h1>}
Jonathan
  • 469
  • 1
  • 6
  • 20
  • 3
    Possible duplicate of [How can I check whether an array is null / empty?](https://stackoverflow.com/questions/2369967/how-can-i-check-whether-an-array-is-null-empty) – Engineer Aug 14 '19 at 08:48

5 Answers5

2

You can use length property

  {this.props.items.length == 0 ? errorMessage : <h1>Working</h1>}
Idan
  • 3,604
  • 1
  • 28
  • 33
1

this.props.items && this.props.items.length > 0 ? <h1>Working</h1> : errorMessage

Mukesh Soni
  • 6,646
  • 3
  • 30
  • 37
1

Fist check weather Array exists or not then check the length of Array greater than 0, always use double negations to convert that array into bool type

{!!this.props.items && this.props.items.length > 0 ? <h1>Working</h1> : errorMessage}
Harsh kurra
  • 1,094
  • 1
  • 9
  • 19
1

Check the lodash library. It's very helpful for that kind of needs.

https://lodash.com/docs/4.17.15#isEmpty

With this you could just use:

{isEmpty(this.props.items) ? errorMessage: <h1>Working</h1>}

pawelbylina
  • 1,387
  • 10
  • 17
0

Safer to check with the type before checking its length, as type string can return length as well

{ Array.isArray(this.props.items) && this.props.items.length < 1 ? errorMessage : <h1>Working</h1> }
Jee Mok
  • 6,157
  • 8
  • 47
  • 80