React CookBook: Check Mark as Completed or Not

Hi @TurtleWolf1, there are actually a couple of issues with that markAsCompleted method:

  • You’re attempting to spread an object into an array, which yields that “foundTask is not iterable” error – what would work is

    this.setState({
      items: [
        ...this.state.items,
        {...foundTask}
      ]
    })
    
  • However, this way you would append the modified item to the list, not modify it in place;

  • And either way, you’re still mutating the original item and only making a copy afterwards

So try this instead:

markAsCompleted = id => {
  // First, make a copy of the existing items
  const [...items] = this.state.items
  // Then find the index of the item you want to modify
  const index = items.findIndex(task => task.id === id)
  // Now you can replace the item with a modified copy of the found item
  const foundItem = items[index]
  items[index] = { ...foundItem, completed: !foundItem.completed }
  // Finally, set the items to the modified copy of the original array
  this.setState({ items });
}

BTW also note the warning regarding componentWillMount().