DEV Community

umasankar-swain
umasankar-swain

Posted on

How to check any property of State has any null value or not

Here is the state of my App:

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

Here is the code of condition in which I am trying to achive, if any property of the state has null value then return true otherwise return false.

const isNullish = Object.values(state).every(value => {
        if (value==='' && value===0 && value === []) {
          return true;
        }
        return false;
      });
console.log(isNullish)
console.log(state)
Enter fullscreen mode Exit fullscreen mode

But the chalenge is whenever I execute that code in my app it returns false although the properties has no value.Below is the console output of above code:

false
SpecialPrice.jsx:124 {priceType: 0, recurrenceType: 0, start_date: '', end_date: '', 
minCapacity: 0, …}
days: []
end_date: ""
max: 0maxCapacity: 0
min: 0
minCapacity: 0
price: 0
priceType: 0
recurrenceType: 0
start_date: ""
[[Prototype]]: Object
SpecialPrice.jsx:129 []
Enter fullscreen mode Exit fullscreen mode

For better understanding I have attached a screenshot here:

Image description

Thanks in advance....

Top comments (4)

Collapse
 
joelbonetr profile image
JoelBonetR 🥇

What's the use case for that? I don't quite get it 😅

Collapse
 
umasankarswain profile image
umasankar-swain

Use case is,I want to check wheather the all properties of the state have values or not...

Collapse
 
joelbonetr profile image
JoelBonetR 🥇 • Edited

The use case would be (according to the screenshot) to have some sort of validation for the form.

In which case you can apply

Which will be compliant with any RFC. This is because the implementation goes on the browser by default and currently the DOM is a pretty good state that we've available by default, no need to add more complexity using React managed forms unless it's one edgy case in which it does make sense 100%.

If you need further validations (such comparing two different inputs to ensure end date is posterior to the initial date or a max is higher than a min) then I'd set a function on form submit like that:

const [isValid, setIsValid] = useState(false);

const validateMinMax = (min, max) => min < max; 

const validate = (e) => {
  e.preventDefault();
  const min = e.target.querySelector('#min').value;  
  const max = e.target.querySelector('#max').value;

  /*
    if you have multiple validations I'd use an AND to set the value for isValid.
    E.g.  const valid = validateMinMax( min, max) && validateWhatever(inputValue);
           setIsValid(valid);
  */  

  setIsValid( validateMinMax(min, max) );
}

useEffect( () => {
  if( isValid ) // send POST request to the server
  else // show error in the form, near the submit button
}, [isValid]);

return (<Form onsubmit={(e) => validate(e)}>
               <input type="number" id="min" name="min">
               <input type="number" id="max" name="max">
               {/* other inputs and submit button */}
            </Form>);
Enter fullscreen mode Exit fullscreen mode

This way you just save a state about whether the entire form it's valid or not. Maybe you need to validate each item individually and you do prefer not to use the standard html + attrs + CSS way, in which case your state will look like that:

const [valid, setIsValid] = useState({
    priceType: false,
    recurrenceType: false,
    start_date: false,
    end_date: false,
    minCapacity: false,
    maxCapacity: false,
    price: false,
    min: false,
    max: false,
    days: false
});
Enter fullscreen mode Exit fullscreen mode

So your validations are going in a different place and you just keep track about whether each input is valid or not. That's because unless you mess it up with React States, the value of each input is effectively stored in the DOM.

So you could do

const isTheFormValid = (arr) => arr.every( value => value === true);

const validated = isTheFormValid( Object.values(state) );

console.log( validated ) // true if everything's OK || false if one or more are wrong
Enter fullscreen mode Exit fullscreen mode

Plus you can reuse the isTheFormValid function somewhere else and everything gets more maintainable, less coupled and more understandable.

I think this covers your question/needs but answer if it doesn't 😀

Best regards

Edit: If for any reason you do prefer to keep the current implementation overall and just fix this specific thing in this specific use-case, @sote 's answer is perfectly fine.

Collapse
 
sote profile image
sote

it should be
if (value === '' || value === 0 || Array.isArray(value) && value.length === 0)