Home > Mobile >  How can i get the Id of the Todo
How can i get the Id of the Todo

Time:01-23

am trying to delete am item by id but i keep get error, that each child should have a unique key after giving a it an id, what am i doing wrongly, why am i not getting the id

const TodoList = () => {

    const [input, setInput] = useState("");
    const [todos, setTodos] = useState([])

    const handleSubmit = e => {

        e.preventDefault()

        setTodos([...todos, input])
        setInput("")
    }

    const handleDelete = id => {

       let item =  todos.filter(todo => todo.id !== id)

       console.log(item)
    //    setTodos(item)
    }




  return (
  <div className='todolist'>
      <h2>Todo List</h2>
      <form>
          <input value={input} onChange={e => setInput(e.target.value)} placeholder='write something' />
          <button onClick={handleSubmit}>Add todo</button>
      </form>
      {todos.map(todo => (

          <div key={todo.id}  className='todolist__details'>
              <h2>{todo}</h2>
              <DeleteIcon onClick={() => handleDelete(todo.id)} />
          </div>
      ))}
  </div>
  );
};

export default TodoList;

CodePudding user response:

 {todos.map((todo, i) => {
        <div key={i}  className='todolist__details'>
              <h2>{todo}</h2>
              <DeleteIcon onClick={() => handleDelete(i)} />
          </div>
    })}

You can check how list and keys work in react in here

https://reactjs.org/docs/lists-and-keys.html

CodePudding user response:

From the above code, it looks like todos is an array of strings. So when you are assigning key by doing todo.id, you are assigning the key to be undefined since the id property does not exist in the string type. Change you map method like this

{todos.map((todo, i) => (
    <div key={i}  className='todolist__details'>
        <h2>{todo}</h2>
        <DeleteIcon onClick={() => handleDelete(i)} />
    </div>
))}

and then change on your handleDelete like

const handleDelete = id => {
    const newTodos = [...todos];
    newTodos.splice(id, 1);
    console.log(newTodos)
    setTodos(newTodos)
}

CodePudding user response:

You have not given id to any of your todo , Pass the index of that todo instead of id , it will solve your problem Try this sandbox code link

I hope you find this helpful.

  •  Tags:  
  • Related