Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to delete a task in react functional component hooks

I am trying to delete a task using handleDelete function, but something get my attention and i don’t know why!
Every time i press the addTodos function, the handleDelete is triggered automatically why is that ?

My aim is to get the id once i press a tag inside the map, but as a weird thing to a beginner as myself i don’t know why once i press the Add button the handleDelete function runs ?

My code :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

     import { useState } from "react";
     import "./App.scss";

      function App() {
        //Value of Input
        const [val, setVal] = useState("");

      const [todos, setTodos] = useState([]);

      const addTodos = (e) => {
          e.preventDefault();
          setTodos([...todos, val]);
          setVal("");
       };

      const handleDelete = (id) => {
          console.log(id);
       };

      return (
        <div className="App">
        {/** On change values*/}
       <form onSubmit={addTodos}>
        <input
             onChange={(e) => setVal(e.target.value)}
             value={val}
             type="text"
         />
         <button type="submit">Add</button>
       </form>
       <ul>
          {todos.map((todo, key) => (
           <div key={key}>
              <li>{todo}</li>
              <a onClick={handleDelete(key)}>X</a>
           </div>
            ))}
       </ul>
      </div>
      );
      }

      export default App;

I tried to console log inside the id inside handleDelete function but the console is also triggered from the addTodos function as well!

>Solution :

Change this:

onClick={handleDelete(key)}>X</a>

To this:

onClick={()=> handleDelete(key)}>X</a>

In the first case, you are calling the function handleDelete and pass its return value as an event handler.

In the second case, you are passing a function definition as an event handler, which is the proper way of doing this.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading