Trying to delete an item from a list of items

I am trying to delete an item from a list of items, but it deletes all the items in the list when page loads, i am sure its because of the map, i cant think of a way to fix this without making a detail page for the todos but i dont want to make a detail page for the todo item, any help will be appreciated

 let deleteTodo = async(id) => {
    console.log(id)
    fetch(`http://localhost:8000/api/delete/${id}/`, {
      method: "DELETE",
      headers: {
        "Content-Type": "application/json"
      },
    })
  }

 return (
    <div className="App">
      <div>
        <div>

          
          <form onSubmit={handleSubmit}>
            <label>
              Title:
              <input type="text" placeholder='Title here' onChange={handleInputChange} name="title" value={values.title} />
            </label>
            <br></br>
            <br></br>
            <label>
              Body:
              <input type="text" placeholder='Body here' onChange={handleInputChange} name="body" value={values.body} />
            </label>
            <br></br>
            <br></br>
            
            <input type="submit" value="Submit" />
          </form>

        </div>

        <div>
          {todos.map((todo, index) => (
            <div key={index}>
              <h1>{todo.title}</h1>
              <h4>{todo.body}</h4>
              <button onClick={deleteTodo(todo.id)}>delete</button>
            </div>
          ))}
        </div>

      </div>
    </div>
  );
}

Button callback is immediately invoked upon rendering.

<button onClick={deleteTodo(todo.id)}>delete</button>

Should be called in a callback handler function.

<button onClick={() => deleteTodo(todo.id)}>delete</button>

Or make deleteTodo a curried function so it's immediately invoked and closes over the passed id value and returns a function to be called when button is clicked.

const deleteTodo = (id) => () => {
  console.log(id);
  fetch(`http://localhost:8000/api/delete/${id}/`, {
    method: "DELETE",
    headers: {
      "Content-Type": "application/json"
    },
  })
};

...

<button onClick={deleteTodo(todo.id)}>delete</button>
Back to Top