2

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) }} />
iceveda06
  • 545
  • 7
  • 18
DCR
  • 10,658
  • 7
  • 38
  • 86

2 Answers2

2

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.

PanJunjie潘俊杰
  • 3,190
  • 1
  • 13
  • 22
1

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

iceveda06
  • 545
  • 7
  • 18