Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

reactjs

This is a piece of a React Component:

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

 handleClick (event) {
     this.setState((prevState, props) => {
         counter: props.counter + 1
     });
     console.log(this.state.counter);
 }

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

/Volumes/Development/react-hello-world/src/App.js
  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
 });

with

 this.setState({
     counter: props.counter + 1
 });

it works?

like image 533
sensorario Avatar asked Oct 18 '22 21:10

sensorario


1 Answers

Because

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.

like image 106
dfsq Avatar answered Oct 21 '22 03:10

dfsq