1

I'm working on a To Do application and when I check one box off and delete it the next in the list gets mark completed. I'm not sure what's going wrong

Tried using splice and filter, at first I thought it was because splice was using the index but I switched to using filter and have the same problem.

```react

function ToDoList() {
  const [toDos, setToDos] = useState([
    {id: uuid(), toDo: "Workout", done: false},
    {id: uuid(), toDo: "Grocery shopping", done: false},
    {id: uuid(), toDo: "Cook dinner", done: false},
    {id: uuid(), toDo: "Walk dog", done: false},
    {id: uuid(), toDo: "Do laundry", done: false},
  ])
  // const removeToDo = index => {
  //   const newToDos = [...toDos];
  //   newToDos.splice(index, 1);
  //   setToDos(newToDos);
  // }

```switched to filter

const removeToDo = toDoId => {
    const newToDos = toDos.filter(toDo => toDo.id !== toDoId);
    setToDos(newToDos);
  }
  return (
    <StyledToDoList>
      <div className="ToDoContainer">
        <header className="ToDoHeader">To-Do List</header>
        <ToDoForm addToDo={addToDo} />
        <ul className="ToDoList">
          {toDos.map((toDo, index) => (
            <ToDo
              id={toDo.id}
              toDo={toDo}
              index={index}
              key={`${toDoInfo.id}${index}`}
              removeToDo={removeToDo}
            />
          ))}
        </ul>
        <RemoveChecked />
      </div>
    </StyledToDoList>
  )
}

function ToDo({ toDo, removeToDo }) {
  const [value, setValue] = useState(false)
  return (
    <StyledToDo>
      <li className="ToDoWrapper">
        <Checkbox
          id={toDo.id}
          isOn={value}
          handleToggle={() => setValue(!value)} 
        />
        <span className="ToDoItem">{toDo.toDo}</span>
        <button className="ToDoButton" type="button" onClick={() => removeToDo(toDo.id)}>
          &times;
        </button>
      </li>
    </StyledToDo>  
  )
}

Expected after deleting checked list item, the next one remains unchecked, but it marks the next one complete.

1 Answers1

0

Not sure if this will fix it, but try adding event as a second argument sent to removeToDo().

<button className="ToDoButton" type="button" onClick={(event) => removeToDo(toDo.id, event)}>

And then in removeToDo() add two lines (and don't forget to pass in event as a second parameter):

const removeToDo = (toDoId, event) => {
    event.preventDefault()
    event.stopPropagation()
    const newToDos = toDos.filter(toDo => toDo.id !== toDoId);
    setToDos(newToDos);
}

preventDefault() stops any default behaviour by the browser when this particular action is performed.

stopPropagation() stops the event from bubbling up the event chain.**

** What's the difference between event.stopPropagation and event.preventDefault?

Joss Classey
  • 1,054
  • 1
  • 7
  • 22