Tutorials / Modern JavaScript: Async, Modules and the Browser / Final project: a post explorer with modules and fetch

Final project: a post explorer with modules and fetch

28 min read javascript
Course contents (16 lessons)
  1. Modern syntax
  2. Destructuring, spread and rest
  3. ES modules: import and export
  4. Objects, this and errors
  5. Classes and prototypes
  6. Understanding this in JavaScript
  7. Error handling: try, catch and custom errors
  8. Asynchronous JavaScript
  9. The event loop: how JavaScript handles waiting
  10. From callbacks to promises to async/await
  11. Fetch and REST APIs
  12. Working in the browser
  13. Local storage and session storage
  14. Debugging with browser DevTools
  15. Performance basics: debounce and throttle
  16. Node.js essentials
  17. Node.js and npm basics
  18. Working with files in Node.js
  19. A tiny HTTP server with Node.js
  20. Testing and the final project
  21. Testing basics with the Node.js test runner
  22. Final project: a post explorer with modules and fetch

What we are building

A page that loads posts from a public API, lets you search them as you type, and lets you mark favourites that are remembered after a reload. It uses what the course covered: modules, destructuring, fetch with error handling, async/await, debounce, localStorage, and the DOM.

We use JSONPlaceholder, the free practice API from the fetch lesson. The project has five files in one folder:

index.html
main.js
api.js
storage.js
utils.js

Remember that module scripts need a web server. Run npx serve . in the folder, or use Live Server in VS Code.

utils.js

// utils.js
export function debounce(fn, delay) {
  let timer;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), delay);
  };
}

export function el(tag, props = {}, ...children) {
  const node = document.createElement(tag);
  Object.assign(node, props);
  node.append(...children);
  return node;
}

debounce is the one from the performance lesson. el is a tiny helper to create elements. Object.assign(node, props) copies properties like className or textContent onto the node, and append(...children) adds text or elements. It keeps the rendering code short, and because we only assign textContent, never innerHTML, user text cannot inject markup.

storage.js

// storage.js
export function load(key, fallback) {
  try {
    const raw = localStorage.getItem(key);
    return raw === null ? fallback : JSON.parse(raw);
  } catch {
    return fallback;
  }
}

export function save(key, value) {
  try {
    localStorage.setItem(key, JSON.stringify(value));
  } catch {
    // storage may be full or blocked, the app still works without it
  }
}

This is the safe wrapper from the storage lesson. The rest of the app does not need to care about null or parse errors.

api.js

// api.js
const BASE_URL = "https://jsonplaceholder.typicode.com";

export async function getPosts({ signal } = {}) {
  const response = await fetch(`${BASE_URL}/posts?_limit=40`, { signal });
  if (!response.ok) {
    throw new Error(`Could not load posts (HTTP ${response.status})`);
  }
  return response.json();
}

We pass an optional signal, so that the caller can cancel the request. Checking response.ok turns a 404 or 500 into a real error that our try/catch in main.js will handle.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Post explorer</title>
  <style>
    body { font-family: system-ui, sans-serif; max-width: 640px; margin: 2rem auto; padding: 0 1rem; }
    input { width: 100%; padding: .6rem; font-size: 1rem; box-sizing: border-box; }
    li { display: flex; justify-content: space-between; gap: 1rem; padding: .6rem 0; border-bottom: 1px solid #ddd; }
    li button { border: 0; background: none; cursor: pointer; font-size: 1.2rem; }
    .status { color: #666; margin: .8rem 0; }
  </style>
</head>
<body>
  <h1>Post explorer</h1>
  <input id="search" type="search" placeholder="Search titles...">
  <p id="status" class="status"></p>
  <ul id="list"></ul>
  <script type="module" src="main.js"></script>
</body>
</html>

main.js

// main.js
import { getPosts } from "./api.js";
import { load, save } from "./storage.js";
import { debounce, el } from "./utils.js";

const searchInput = document.querySelector("#search");
const statusText = document.querySelector("#status");
const list = document.querySelector("#list");

let posts = [];
let favourites = new Set(load("favourites", []));
let term = "";

function visiblePosts() {
  const query = term.trim().toLowerCase();
  return posts.filter(({ title }) => title.toLowerCase().includes(query));
}

function render() {
  const items = visiblePosts();
  statusText.textContent = `${items.length} of ${posts.length} posts, ${favourites.size} favourites`;
  list.replaceChildren();

  for (const { id, title } of items) {
    const isFav = favourites.has(id);
    const star = el("button", {
      textContent: isFav ? "★" : "☆",
      title: isFav ? "Remove from favourites" : "Add to favourites",
    });
    star.dataset.id = id;
    list.append(el("li", {}, el("span", { textContent: title }), star));
  }
}

list.addEventListener("click", event => {
  const button = event.target.closest("button[data-id]");
  if (!button) return;

  const id = Number(button.dataset.id);
  if (favourites.has(id)) favourites.delete(id);
  else favourites.add(id);

  save("favourites", [...favourites]);
  render();
});

searchInput.addEventListener("input", debounce(event => {
  term = event.target.value;
  render();
}, 250));

async function init() {
  statusText.textContent = "Loading posts...";
  try {
    posts = await getPosts();
    render();
  } catch (error) {
    console.error(error);
    statusText.textContent = "Could not load posts. Check your connection and reload.";
  }
}

init();

How the pieces fit together

Modules. Each file has one job. api.js knows about the network, storage.js about the browser storage, utils.js about small helpers, and main.js joins them. If the API address changes, you edit one file.

State. There are three pieces of state: posts, favourites and term. The render() function draws the page from them. Events only change the state and call render(). This is the same pattern as the to-do project in the fundamentals course.

Destructuring. ({ title }) => ... and for (const { id, title } of items) unpack the post objects in place.

Set for favourites. A Set stores unique values and has fast has, add and delete. We convert it to an array with spread, [...favourites], to save it as JSON.

Debounce. The search runs 250 ms after the user stops typing, not for every key.

Event delegation. One listener on the list handles every star button, even after the list is rebuilt.

Error handling. init wraps the fetch in try/catch and shows a message when it fails. The user always sees one of three states: loading, loaded, or failed.

Common mistakes

  • **Opening index.html from the file system.** Modules need a server.
  • **Forgetting .js in the import path.** Write ./api.js.
  • Saving a Set directly. JSON.stringify(new Set([1])) gives {}. Convert it to an array first.
  • Comparing id types. dataset.id is a string, so we convert with Number.
  • **Skipping the response.ok check.** A 500 error would make response.json() fail with a confusing message.

Try it yourself

  1. Add a "Show favourites only" checkbox that filters the list.
  2. Show the post body in a detail area when you click a title, loading it from /posts/{id}.
  3. Use an AbortController so a slow, old request never replaces a newer one.
  4. Move visiblePosts into its own module, write three tests for it with node:test, and run them in Node.
javascript
// utils.js
export function debounce(fn, delay) {
  let timer;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), delay);
  };
}

export function el(tag, props = {}, ...children) {
  const node = document.createElement(tag);
  Object.assign(node, props);
  node.append(...children);
  return node;
}

This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.

Sign up free I already have an account