Ashh
Ashh

Reputation: 46441

warning Expected an assignment or function call and instead saw an expression

When i use this line:

this.state.selectedJobType.length > 0 ? 
    '' 
    : 
    this.setState({ jobTypeErrMsg: 'Please select at least one job type'});

It throws error:

warning Expected an assignment or function call and instead saw an expression:

Upvotes: 2

Views: 3660

Answers (1)

Mayank Shukla
Mayank Shukla

Reputation: 104369

Because ternary operator return the values on the basic of condition, and you are using ternary operator to update state, that's why.

condition ? expr1 : expr2;

Ternary operator execute the expressions [expect the expressions that should result to some value, that can be a function call or directly any value] and return the result of that expressions.

Use if condition instead of ternary operator, like this:

if(this.state.selectedJobType.length)
   this.setState({ jobTypeErrMsg: 'Please select at least one job type'})

Ternary operator works to assign the value on the basis of condition, like this:

let a = 0==0 ? 1 : 0;

Or you can use that inside JSX for conditional rendering, like this:

<div>{ 0==0 ? 'true' : 'false' }</div>

Or to call other function on the basis of condition:

1==1 ? a() : b();

DOCs:

Returns one of two expressions depending on a condition. If condition is true, the operator returns the value of expr1; otherwise, it returns the value of expr2.

Upvotes: 4

Related Questions