Noob_Mern_Dev
Noob_Mern_Dev

Reputation: 83

How to check whether the state has no empty value In React app,

This is the state of the Application. Validate function should return true if there are non zero, non empty and non empty array inside the state...

const [state, setState] = useState({
    priceType: 0,
    recurrenceType: 0,
    start_date: '',
    end_date: '',
    minCapacity: 0,
    maxCapacity: 0,
    price: 0,
    min: 0,
    max: 0,
    days: []
});

I'm trying in this way but not giving correct result,

const validate=Object.values(state).every((item)=>(item===0 && item==='' && item===[]))

Any suggestion....

Thanks in advance

Upvotes: 1

Views: 1429

Answers (1)

Ori Drori
Ori Drori

Reputation: 191976

Standard equality (== or ===) doesn't work with objects (and arrays):

console.log([] === []) // false
console.log({} === {}) // false

In addition, you can't use && because logically and usually item can't be 0 , an empty string, and an empty array at the same time (there are tricks to do so, but they are not fitting for this question).

To make sure that you don't have empty values use Array.some() to check if it least one is empty, and negate the results. To make sure that all are empty use Array.every().

To check if an array is empty, check that it's length is not 0 (this also works with strings). So you can just check the length, and if that returns undefined, check if it's 0:

const state = {
  priceType: 0,
  recurrenceType: 0,
  start_date: '',
  end_date: '',
  minCapacity: 0,
  maxCapacity: 0,
  price: 0,
  min: 0,
  max: 0,
  days: []
};

const validate = !Object.values(state)
  .some(item => item === 0 || item.length === 0);
  
console.log(validate);

Upvotes: 3

Related Questions