Lesson 5 โ€” Pull Data In

fetch ยท the page loads the herd from a file by itself

The list should not live inside the program forever. On a ranch the record book is a separate thing. Fetch is how the page walks over and gets that file.

Here is the finished look

This preview loads the herd from a file named herd.json. If the names show up, fetch worked.

Step 1 โ€” a file that is only data

Create herd.json next to index.html. Same animals, no JavaScript wrapped around them. Start with one, then put all four in the array. Comma between animals. No comma after the last one.

[
  {
    "name": "Black Gold",
    "tag": "FW-01",
    "breed": "Texas Longhorn",
    "notes": "Rare black pattern, 100\"+ horns",
    "startWeight": 1100,
    "currentWeight": 1280
  }
]

Step 2 โ€” go get it

Replace the hard-coded list in script.js with a fetch. The page asks for the file, reads it as data, then builds the table the same way as last lesson.

fetch("herd.json")
  .then(function (response) { return response.json(); })
  .then(function (herd) {
    var tbody = document.getElementById("herd-body");
    tbody.innerHTML = "";
    herd.forEach(function (animal) {
      var gain = animal.currentWeight - animal.startWeight;
      tbody.insertAdjacentHTML("beforeend",
        "<tr><td>" + animal.name + "</td><td>" + animal.tag + "</td><td>" +
        gain + " lbs</td></tr>"
      );
    });
  })
  .catch(function () {
    document.getElementById("herd-body").innerHTML =
      "<tr><td colspan='3'>Could not load the herd file.</td></tr>";
  });

A thing that will confuse you once

If you double-click index.html on your computer, fetch often fails. Browsers block a page on your disk from opening other files. That is the browser being careful, not your JSON being wrong. It works on a real site โ€” like this one โ€” or a tiny local server.

That is the first Howdy World project: bones, paint, math, data, fetch. Garden sensors come later. Same idea. Keep building.

โ† Lesson 4 All lessons Open finished demo โ†’