user10374052
user10374052

Reputation:

How to solve Error Use object destructuring prefer-destructuring - React

I am stuck with an ugly issue which I am unable to resolve. I am beginner in React.

This is my Code

handleCheckChildElement(event) {
    let items = this.state.items;
    items.forEach(items = () => {
        if(items.value === event.target.value) {
            items.isChecked = event.target.checked;
        }
    });
    this.setState({ items });
}

This is the image of the error - Error Image

Upvotes: 3

Views: 1608

Answers (3)

user10334760
user10334760

Reputation:

handleCheckChildElement(event) {
   const items = this.state.items;
   const filtered = items.filter(item => item.value === event.target.value)
   .map(item => item.isChecked  = event.target.checked) ;
   this.setState({items : [...filtered] );
}

Upvotes: 0

Hemadri Dasari
Hemadri Dasari

Reputation: 34014

Your code can be improved to something like below. Please find relevant comments in the code below for your better understanding

   handleCheckChildElement(event) {
           const { items } = this.state; //extract state values like this to a const variable 
           const newItems = items.map(item => { //do map on items because map returns a new array. It’s good practice to use .map than forEach in your case
                if(item.value === event.target.value) {
                         item.isChecked = event.target.checked;
                         return item; //return updated item object so that it will be pushed to the newItems array
                }
                return item; // return item because you need this item object as well
            });
           this.setState({ items: newItems}); //finally set newItems array into items
          }

Upvotes: 0

Vishal
Vishal

Reputation: 10964

Use below code for line #55 :

let {items}= {...this.state};

Read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring

Upvotes: 1

Related Questions