Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary operator for Setstate

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?


1 Answers

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.

like image 99
raina77ow Avatar answered Dec 30 '25 17:12

raina77ow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!