Bryan
Bryan

Reputation: 41

Using arrow function with curly braces and ternary operator for setState's callback error?

I set an arrow function with a ternary operator in curly braces as the callback for setState but get an error message when I run the code.

  1. If I remove the curly braces, the error goes away.
  2. If I don't use a ternary operator the error goes away.
  3. If I write "return" before the operator the error goes away.

The code works both ways (it looks like it runs some rescue method), but I don't understand why I am getting the error message to begin with. The function I am running doesn't need to return anything, just needs to run some statements. But it seems like React doesn't like ternary operators in callbacks? or they are ok if they are returned? does anyone know why?

    this.setState({someObject},() => { x ? console.log("yo") : null;}); 

warning message

 Expected an assignment or function call and instead saw an expression  no-unused-expressions

something wrong with ternary operators in callback functions?

Upvotes: 2

Views: 1671

Answers (3)

Jack
Jack

Reputation: 491

The answer has to do with how arrow functions work:

When you write an arrow functions without curly braces then whats on the right of the arrow is considered an expression and JS knows to return the result of the expression.

But when curly braces are used then what is on the right of the arrow is a statement block which doesn't return anything unless instructed to therefore a return statement must be given implicitly in order for the function to return anything.

Upvotes: 0

supra28
supra28

Reputation: 1636

Its an ESLint warning, It is happening because you are not using the value that you have returned anywhere else and has no effect on the state of the program.

Unused expressions are those expressions that evaluate to a value but are never used

you can read more about the rule here: ESLint

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370699

The problem is that you aren't returning the result of the ternary expression (or doing anything with it), and the ternary operator is meant to be used when you need the resulting value. For similar reasons, the following lines would produce the same warning:

function foo() {
  'bar';
 }

and

function foo2() {
  baz === 3;
 }

The value of the evaluated expression is being discarded, just as it is in your situation. When you don't need to use the result of the expression, don't use the ternary operator; use if and else instead:

this.setState({someObject},() => {
  if (x) console.log("yo");
}); 

Upvotes: 0

Related Questions