sensorario sensorario - 7 months ago 63
React JSX Question

Why ReactJs says "warning 'counter:' is defined but never used" but variable is used?

This is a piece of a React Component:

constructor(props) {
this.state = {
counter: 0

handleClick (event) {
this.setState((prevState, props) => {
counter: props.counter + 1

Trying to execute this page, browser wite these lines of warning in console:

17:13 warning Using 'LabeledStatement' is not allowed no-restricted-syntax
17:13 warning Unexpected labeled statement no-labels
17:13 warning 'counter:' is defined but never used no-unused-labels
17:22 warning Expected an assignment or function call and instead saw an expression no-unused-expressions

✖ 4 problems (0 errors, 4 warnings)

I am using the counter here: "console.log(this.state.counter);". Why that error message?

Why if I change

this.setState((prevState, props) => {
counter: props.counter + 1


counter: props.counter + 1

it works?



counter: props.counter + 1

means create label named counter. However, you indeed never use this label after.

You probably wanted

this.setState((prevState, props) => ({
  counter: props.counter + 1

Note, that you just need to wrap {} in arrow function with parenthesis. Otherwise {} is considered as function body block and not an object returned from this function function, which you want in your case.