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: []
});
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)
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 []
For better understanding I have attached a screenshot here:
Thanks in advance....
Top comments (4)
What's the use case for that? I don't quite get it 😅
Use case is,I want to check wheather the all properties of the state have values or not...
The use case would be (according to the screenshot) to have some sort of validation for the form.
In which case you can apply
Form input validation WITHOUT JavaScript
JoelBonetR ・ Aug 15 ・ 2 min read
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:
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:
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
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.
it should be
if (value === '' || value === 0 || Array.isArray(value) && value.length === 0)