3

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

1
  • Please share the complete component code to understand better about the issue Commented Dec 6, 2018 at 18:16

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Please wait, the errors are solved. I am trying to run the project.
I have seen that compilation errors are solved but let me run my project in Chrome/Firefox. Please wait , I will definitely mark your answer correct in a short while
@Scooby what happened?
0

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
          }

Comments

0
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] );
}

3 Comments

It would be super nice if you explain what you changed and why you changed. BTW, welcome to SO!
wt?! i wrote this for demonstration. how filter and change it easily... in this example i replaced existing array with filtered result
@David: Even though you are replying a direct question. But it is always nice to write little explanation where questioner made mistake, how you've solved it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.