Skip to the workspace
Pebellslearn by building
The Client Half  ›  Lesson

Click, Fetch, Update

Checkpoint - Interactivity 13 minEvery interaction with a server has four beats: listen for the event, send the request with fetch, check the response status because fetch does not fail on error codes, and update the page from the server's answer.

full stack / Click, Fetch, Update

Explore each scene at your own pace.

01 · The rule

The rule

Click, Fetch, Update

Sprout's "Add plant" form looks simple. Behind it, the browser must notice the submit, send the plant to the server, wait, check the answer, and only then change what the user sees. Skip the checking step and the screen can cheerfully show a plant that was never saved.

The rule

Listen, send, check, update.

Every interaction that talks to a server has these four beats:

form.addEventListener('submit', async (event) => {
  event.preventDefault();                                  // listen

  const res = await fetch('/api/plants', {                 // send
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name: nameInput.value, water_every_days: Number(daysInput.value) }),
  });

  if (!res.ok) {                                           // check
    message.textContent = `Could not save (error ${res.status}).`;
    return;
  }

  const plant = await res.json();                          // update
  list.append(renderPlant(plant));
});
  • Listen. The handler runs on submit. event.preventDefault() stops the browser's old-style form submission, which would reload the whole page.
  • Send. fetch takes a method, headers and a body. JSON.stringify turns the object into text, and Content-Type: application/json tells the server how to read it.
  • Check. fetch only fails outright when no response arrives at all, such as when the network is down. A 400 or 500 still counts as a response, so you must look at res.ok, which is true only for statuses from 200 to 299. (A real app also wraps the call in try/catch to handle the network failing.)
  • Update. Change the page using the server's version of the plant. It carries the id the database just assigned, which later edits and deletes need.

One more guard is worth the two lines it costs: disable the Add button when the request leaves and enable it again when the answer arrives. Otherwise an impatient double-click sends two POSTs, and Asha ends up with two identical Basils.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.