Home > OS >  Why can't i delete my todo item using filter?
Why can't i delete my todo item using filter?

Time:01-02

I'm trying to make the function to delete my todo item but when click on the delete button, nothing happens, is there anything wrong with my codes, plsease help me! Thank you so much!

import React, { useState } from "react";

function App() {
  const [value, setValue] = useState("");
  const [todos, setTodos] = useState([]);

  // you can use the submit itself, no need for an extra addTodo function
  handleSubmit = (e) => {
    console.log("x");
    e.preventDefault();
    setTodos([...todos, value]);
    setValue("");
  };

  deleteTodo = (id) => {
    console.log("delete")
    const removedArr = [...todos].filter(todo => todo.id !== id);

    setTodos(removedArr);
  }

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          onChange={(e) => setValue(e.target.value)}
          type="text"
          placeholder="add todo"
        />
        <button type="submit">Add</button>
      </form>
      {todos.map((todoValue) => (
        <div>
        {todoValue} <button deleteTodo={()=>deleteTodo(id)}>x</button>
        </div>

      ))}
      
  </div>
  );
}
export default App;

Link codesandbox: CodeSandbox

CodePudding user response:

There is two mistakes in your code :

  1. button should call the deleteTodo function when user clicks on that button i.e onClick() function
  2. id is undefined. Please refer to this sandbox code example. I corrected your code and now it is working .Link to sandbox

CodePudding user response:

you should use onClick in button and your list does not have id so use todo instead of todo.id:

      deleteTodo = (id) => {
     const removedArr = [...todos].filter(todo => todo !== id);
        setTodos(removedArr);
      }
    
      return (
        <div>
          <form onSubmit={handleSubmit}>
            <input
              onChange={(e) => setValue(e.target.value)}
              type="text"
              placeholder="add todo"
            />
            <button type="submit">Add</button>
          </form>
          {todos.map((todoValue) => (
            <div>
            {todoValue} <button onClick={()=>deleteTodo(todoValue)}>x</button>
            </div>
    
          ))}
        </div>
      );
    }
    export default App;
  • Related