DCR
DCR

Reputation: 15665

code works but gives: Expected an assignment or function call

why is this causing an unused expression error?

<input style={{margin:'25px 50px 0',textAlign:'center'}}
       type='text' placeholder='add ToDo'
onKeyPress={e =>{(e.key ==='Enter' ? this.addTodo(e.target.value):null) }} />

Upvotes: 2

Views: 93

Answers (2)

JJPandari
JJPandari

Reputation: 3522

iceveda06's answer shows how to fix this, let me explain this eslint rule itself a bit:

Assignments and function calls has side effects (not absolutely correct, an empty function, for example, doesn't have side effect, but in eslint's case, it doesn't go that far to check what the called function exactly do), which is what we ultimately do when writing code, on the other side, expressions alone are valid statements in javascript, e.g. foo ? 1 : 2;, but most of them (except assignments and function calls) don't have any side effect, thus have no contribution for the whole program, so eslint consider them bad code.

Check this question for how to differ expression and statement.

Upvotes: 2

iceveda06
iceveda06

Reputation: 619

You are wrapping your function with { } but not returning any value. Remove { } and it should work since arrow function has an implicit return value otherwise you need to use 'return' to return an answer if you want to wrap it within { }.

Try this:

onKeyPress={e =>(e.key ==='Enter' ? this.addTodo(e.target.value):null) } />

Here is more info, read the part related to 'Function body' topic towards the end: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Upvotes: 1

Related Questions