Narayanan S
Narayanan S

Reputation: 127

Having trouble checking if an array has data or is empty in ReactJS

I have array in my state I set my state default value to an empty array []. After an API request loads I need to use loader until data is ready. So U use condition like:

(if array length  === 0  loader will show otherwise data will show)

but when the API returns empty data I want to show no data available.

What is best way to do that?

My code is below - how can I check the condition if the API returns an empty result?

this.state.offer.length == 0 ?  <Loader /> : <OfferList />

Upvotes: 1

Views: 11779

Answers (4)

Kashif ali
Kashif ali

Reputation: 149

Ideally, you should not show or hide the loader on the basis of the size of your array it should depend on your AJAX call.

Simply you can put a variable in your state like "isLoading", mark it true on making ajax call and mark it false on response independent of whether it is a success or failure.

this.state ={ offer: [], isLoading: false }

on ajax, call

this.setState({isLoading:true});

on the response, call

this.setState({isLoading:true});

and you can display

no data available on the basis of size of array.

Upvotes: 0

Sajith Edirisinghe
Sajith Edirisinghe

Reputation: 1727

Best approach would be to use the ternary operation. First initialize offer to be undefined and you API returns an empty array if there is no data. Next use below expression in render method().

{this.state.offer === undefined ? <Loader /> : this.state.offer.length > 0 ? <OfferList /> : "No data Available"}

Upvotes: 2

alechill
alechill

Reputation: 4502

Easiest would be to have the default be undefined rather than an empty array. Then in your render check:

  • undefined means its loading
  • empty array means no data, so show message
  • non-empty array you can shown data

{!this.state.offer ? <Loader /> : this.state.offer.length ? <OfferList /> : <span>No data available</span>}

Upvotes: 7

Vipin Kumar
Vipin Kumar

Reputation: 6546

Add another property in your state denoting processing like below

state = {
  offer: [],
  processing: false
}

then use this property to show/hide your loader.

You can set/unset this property, while you make API call.

Upvotes: -1

Related Questions