🎓 A1Learner
🔍
0 of 50 lessons completed

Editing a Note

Editing a note is a small form that changes one note title. The note keeps its place in the list while its text changes.

The note being edited

const [editingId, setEditingId] = useState(null);

The edit input

<input value={title} onChange={(e) => setTitle(e.target.value)} />

Saving the new title

fetch(API_URL + '/notes/' + id, {
  method: 'PUT',
  body: JSON.stringify({ title }),
});

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' },
  ]);
  const [editingId] = useState(2);
  const [title] = useState('Ship MERN');

  return (
    <div>
      <h1>Notes</h1>
      <ul>
        {notes.map((note) => (
          <li key={note.id}>
            {editingId === note.id ? (
              <>
                <input value={title} onChange={() => {}} />
                <button>Save</button>
              </>
            ) : (
              note.title
            )}
          </li>
        ))}
      </ul>
    </div>
  );
}

Key points

  • An editing flag in state marks the note being edited, or none.
  • The edit form shows the current title in a controlled input.
  • Saving sends a PUT request with the new title.
  • Saving also updates the note in local state.

In this example, the editing flag marks the second note. The first render shows an edit box for 'Ship MERN'. The other two notes show plain text. The box holds the current title, ready to change. In the real app, saving sends a PUT request with the new title and updates the note in state.

Note

Only one note is edited at a time, so the flag holds one id.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What marks the note that is being edited?