🎓 A1Learner
🔍
0 of 50 lessons completed

Deleting a Note

Deleting a note is a button that asks the API to remove one note. The list then drops that note from state.

A Delete button for each note

<button onClick={() => handleDelete(note.id)}>Delete</button>

The DELETE request

fetch(API_URL + '/notes/' + note.id, { method: 'DELETE' });

Dropping the note from state

setNotes(notes.filter((n) => n.id !== id));

Example

import { useState } from 'react';

export default function App() {
  const [notes] = useState([
    { id: 1, title: 'Buy milk' },
    { id: 2, title: 'Ship MERN' },
    { id: 3, title: 'Read a book' },
  ]);

  return (
    <div>
      <h1>Notes</h1>
      <ul>
        {notes.map((note) => (
          <li key={note.id}>
            {note.title} <button>Delete</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

Key points

  • Each note row carries its own Delete button.
  • The button handler receives the note id as an argument.
  • The handler sends a DELETE request for that id.
  • The handler also removes the note from local state, so the list updates at once.

In this example, the first render shows the three seed notes, and each row carries a Delete button. In the real app, clicking a button sends a DELETE request for that note id. The handler then drops the note from state, so the row leaves the list at once.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

How does the Delete button know which note to remove?