Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 39 ยท Projects

Project: Weather Dashboard

Build a weather dashboard against a mock forecast API: units toggle without refetching, an in-memory cache, stale data on failure, a retry button and live announcements.

A weather card looks like a toy, yet it forces you to solve four problems that every real data-driven interface faces. The data is remote and slow, so you need loading and error states. The same data is requested again and again, so you want a cache. Failures happen, so the screen needs a retry path and ideally something useful to show anyway. And the display changes without a page reload, so people using screen readers need to be told what changed.

We will build the dashboard in three steps: the unit conversions, a small cache, and the complete interface. As in the previous project, a function called mockFetch plays the server: it answers GET /api/forecast?city=... with real Response objects after a short delay. The data is invented and fixed, so every run behaves the same. Replace mockFetch with fetch and a real endpoint when you build your own.

The plan

The mock API returns one JSON document per city:

JSON
{
  "city": "Lisbon",
  "current": { "tempC": 21, "condition": "Sunny", "windKmh": 14 },
  "days": [
    { "day": "Mon", "highC": 23, "lowC": 15, "condition": "Sunny" }
  ]
}

The server always speaks metric. The interface offers metric and imperial, and here is the first design decision: switching units must not call the server. The numbers are the same; only their presentation changes. Converting in the browser is instant, uses no bandwidth and works offline. The rule of thumb is to store data in one canonical form and convert at the edges, when you display it.

flowchart TD
  A["Choose a city"] --> B{"Fresh entry in cache?"}
  B -->|"yes"| F["Show cached forecast"]
  B -->|"no"| C["GET /api/forecast"]
  C -->|"success"| D["Save in cache, show it"]
  C -->|"failure"| E{"Older cached copy?"}
  E -->|"yes"| G["Show it, marked as saved data"]
  E -->|"no"| H["Show error and Retry button"]
  H -->|"Retry"| C

The decision flow for one forecast request: fresh cache first, then the network, then stale data, and only then an error.

Step 1: unit conversion

Keep conversion in tiny pure functions so you can check them against known values. Round only when you display a number, never in the stored data, or repeated conversions would drift.

JS Unit conversion helpers

Press Run (or Ctrl + Enter) to see the console output here.

No output.

-40 is the classic sanity check: both scales meet there, so the output must be -40ยฐ. The rounding happens in format... only, so converting 21 degrees to Fahrenheit gives 70ยฐ on screen while the stored value stays exactly what the server sent.

Step 2: a cache with a time limit

A cache is a Map plus a rule for when an entry is too old. We give each entry a time to live (TTL): within the TTL the entry is fresh and can be used without asking the server; after it, the entry is stale and a new request is needed. Notice the small design choice in the code below: get() does not delete expired entries, it reports fresh: false. That lets the caller decide to use a stale copy as a fallback when the network fails.

To test time-dependent code without waiting, the cache takes the clock as a parameter. Production code uses the default (Date.now); the test passes a fake clock that we move by hand.

JS A cache with a TTL and a fake clock

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first line says miss, the next two say fresh: true, the 15-second line says fresh: false but still returns the value, and saving again resets the age. An in-memory cache disappears when the page closes, which is fine for a dashboard that is open for a few minutes. See caching and polling for HTTP caching, which the browser can do for you.

Step 3: the complete dashboard

Now we assemble the screen. Read the controls first and try them in this order:

  1. Press Refresh a few times and watch the counter "Server requests": within 15 seconds, choosing a city you already loaded uses the cache and the counter does not move.
  2. Click ยฐF ยท mph and back: the numbers change instantly and the counter does not move.
  3. Tick Simulate an outage, then press Refresh. A city you loaded earlier shows its saved copy with a warning. Choose a city you have not loaded yet, such as Nairobi, and you get the error with a Try again button. Untick the box and press the button.
  4. Choose Atlantis: the server answers 404, and the message comes from the JSON error body.
The weather dashboard

How the pieces fit

One request function, three outcomes. loadForecast walks the decision flow from the diagram. The cached copy is read once at the top (to answer from it) and once in the catch (to fall back to it). Reading again in the catch matters: the age shown to the user is the age now, not when the request started.

Stale data on failure. Showing a slightly old forecast with a clear warning is almost always better than an empty error box. The user can decide whether four-minute-old data is good enough. The warning text and the warn styling make it impossible to mistake the old copy for a fresh one.

The ticket guard again. Switching cities quickly starts two requests. Only the response whose ticket is still current may touch the screen, and aria-busy is cleared only by that same latest request. Without this check, a slow Oslo reply could replace the Lisbon card you are now looking at.

Accessible updates. Three techniques work together:

  • A polite live region (role="status") announces what happened ("Forecast for Oslo loaded."). Update its text content; do not move focus for routine updates.
  • aria-busy="true" on the card tells assistive technology the content is being replaced. It is also what our CSS uses to dim the card.
  • When a failure leaves the user with nothing, we move focus to the Try again button so a keyboard user does not have to hunt for it.

Unit buttons use aria-pressed so their on/off state is exposed, and the forecast is a real <table> with a <caption> and row headers, not a grid of divs.

Never put a secret API key in front-end code like this. Anyone can read it in the page source or the Network panel. Real weather services that need a key are called through your own server, which adds the key. See AJAX security.

Ideas to extend it

  1. Auto-refresh every few minutes, but only while the tab is visible (caching and polling).
  2. Retry with backoff for transient 503 errors before showing the error (retries and backoff).
  3. Remember the last city and units with localStorage in your own page. The sandbox here blocks it.
  4. Validate the response so a malformed forecast shows a clear error instead of crashing the render (validating JSON data).
  5. Extract the fetch logic into a reusable module, which is exactly the next-but-one project: a reusable API client.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the units toggle redraw the card without calling the server?

    Store data in one canonical form (metric here) and convert when displaying. A unit switch is a presentation change, not a data change.
  2. 2. In the cache, why does get() return a stale entry with fresh: false instead of deleting it?

    An expired entry is not useful as an answer on its own, but it can be a much better outcome than an error when a refresh fails.
  3. 3. Why does the cache take a now() function as an argument?

    Passing the clock in (dependency injection) lets a test move time by hand instead of waiting 15 real seconds.
  4. 4. Which pair of techniques makes loading and result changes perceivable to screen-reader users?

    A polite live region announces text changes without stealing focus, and aria-busy signals that a region is being replaced.
  5. 5. Why does loadForecast re-read the cache inside the catch block?

    A slow request can take seconds, so the age measured at the start is out of date by the time the failure arrives.

Summary

  • Keep data in one canonical form and convert for display; a presentation change should not cost a request.
  • A cache is a Map plus a TTL rule. Return age and freshness so callers can choose between fresh, stale and missing.
  • On failure, prefer stale data with a visible warning over an empty error. When nothing is available, show the error with a Retry button and move focus to it.
  • Guard against out-of-order responses with a ticket or an AbortController.
  • Announce changes with a role="status" region, mark updating regions with aria-busy, and use aria-pressed for toggle buttons.
  • Inject the clock into time-dependent code so it can be tested without waiting.

Next: Project: To-Do App with a Mock Backend