Ternary operator for Setstate
Is it possible to do this? I want for example set a variable containing the correct state to setState to.
this.setState({
isFiltered: isFilteredCopy,
languagesFilter: isFilteredCopy
});
}
I want to choose either isFiltered or languagesFilter, based on whether the state Array the function which is sent into, is the corresponding one.
Is it possible to also do multiple conditional ternary?
Like I got 4 options to choose based on condition in general?
One possible approach is using computed property name:
this.setState({
[someCondition ? 'isFiltered' : 'languagesFilter']: isFilteredCopy
});
Is it possible to also do multiple conditional ternary? Like I got 4 options to choose based on condition in general?
Syntax allows it, but it'll become confusing. A better option seems to be moving this choice into separate function:
function getFieldName(condition) { ... }
... then calling this function as part of computed property name:
this.setState({
[getFieldName(condition)]: isFilteredCopy
});
As a matter of fact, the whole pattern looks a bit weird; perhaps it might be beneficial to redesign a model instead, depending on use case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With