niina
niina

Reputation: 119

How to display a message if the array of objects is empty using react?

i want to display a message if the object contains data or not. Currently i store the data in state named "data" and set it to null initially.

After getting the request from server store the returned data into data state. If the data state is undefined i display a message "no info". if info has somevalue then i display a message "info available".

This data state if it has data would look like below,

data = [
          { attributes: [],
            info: 'some info',
            meshes: [],
          }
          {attributes: [],
           info: 'someinfo2',
           meshes: [],
           }
           .....so on.... 

       ]

The above is okay..and it displays message "info available"

Now if the info for each object in the data state is empty then should display "no info". so the state would look like below,

  data = [
          { attributes: [],
            info: '',
            meshes: [],
          }
          {attributes: [],
           info: '',
           meshes: [],
           }
           .....so on.... 
          ]

How do i check whether each and every info within data state is empty?

Below is the code which displays message based on data state defined or undefined...

{this.loading ? (
    <div className="spinner"/>) : (
        !this.data ? (
            <div>No info.</div>) :
                (<div>Info available</div>)
        )
    )
)}

Could someone help me solve this. thanks.

Upvotes: 1

Views: 1451

Answers (1)

dfsq
dfsq

Reputation: 193261

You could check if at least some info is not empty by using some method. Maybe like this:

if (this.loading) {
  return (
    <div className="spinner"/>
  )
}

if (this.data && this.data.some((item) => item.info)) {
  return (
    <div>Info available</div>
  )
}

return (
  <div>No info.</div>
)

(I split ternary for readability sake).

Here I use Array.prototype.some - so if at least one info is set it means "Info available". Use this.data.every((item) => item.info) if you need all info items to be set.

Upvotes: 3

Related Questions