Home > Software engineering >  How come value from e.target.parentNode.children[0].innerText never equal to value from filter funct
How come value from e.target.parentNode.children[0].innerText never equal to value from filter funct

Time:01-17

I'm trying to delete ToDo list by event delegation so I placed delete onClick handler on the ul element. Question I have is why toDo != e.target.parentNode.children[0].innerText never equal to true even when I place same value for both elements. So after I add "study" and "eat" for toDo list then click on delete button next to "study", e.target.parentNode.children[0].innerText shows "study" and toDo shows "study" as well, but it doesn't get filtered out. They both have string type so I'm confused. So why doesn't this work?

import './styles.css';
import React, {useState} from 'react';

export default function App() {
  const [toDoList, setToDoList] = useState([]);
  const [value, setValue] = useState([]);

  const addToDo = () => {
    let copyToDoList = [...toDoList];
    setToDoList([...copyToDoList, value]);
    setValue("");
  }

  const deleteToDo = (e) => {
    let copyToDoList = [...toDoList];
    let filteredList = copyToDoList.filter((toDo) => { 
      return toDo != e.target.parentNode.children[0].innerText})
    console.log(filteredList)
    setToDoList(filteredList);
  }

  const handleChange = (e) => {
    setValue(e.target.value);
  }

  return (
    <div>
      <h1>Todo List</h1>
      <div>
        <input value={value} onChange={handleChange} type="text" placeholder="Add your task" />
        <div>
          <button onClick={addToDo}>Submit</button>
        </div>
      </div>
      <ul onClick={deleteToDo}>
        {toDoList.map((toDo, idx) => {
          return(
            <li>
              <span>{toDo} </span>
              <button>Delete</button>
            </li>
            )
        })}
      </ul>
    </div>
  );
}

CodePudding user response:

Try the following command. Then you would see that toDo and e.target.parentNode.children[0].innerText have different lengths.

e.target.parentNode.children[0].innerText has one more lengths than toDo

console.log(toDo.length, e.target.parentNode.children[0].innerText.length);

And the solution is below change this line {toDo} to {toDo}

Remove space.

CodePudding user response:

This happens because you left a space character " " inside the span. This means "aaa" !=="aaa ".

To avoid this error you can add the trim like I did. (but just removing the space is enough...)

const deleteToDo = e => {
    const copyToDoList = [...toDoList]
    const filteredList = copyToDoList.filter( toDo => {
        return toDo !== e.target.parentNode.children[0].innerText.trim()
    })
    setToDoList(filteredList)
}

<ul onClick={deleteToDo} > {
    toDoList.map((toDo, idx) => {
        return (
            <li key={idx}>
                <span>{toDo}</span>
                <button>Delete</button>
            </li>
        )
    })
}</ul>
  • Related