Skip to content
Tutorials Center
My learning

Topics

Lesson 128 of 156 ยท Projects

Project: Weather Dashboard

Build a weather dashboard in plain JavaScript with async/await, a mock API, loading and error states, cancelled requests and Intl formatting.

Most apps you will build spend their lives waiting for data. A weather widget asks a server for the current conditions, shows something useful while it waits, and has to cope when the answer is slow, wrong or never arrives. In this project you will build exactly that kind of app: a small weather dashboard with a city search, a five-day forecast, a ยฐC/ยฐF switch and friendly loading and error screens.

The TryIt sandbox has no network access, so the dashboard talks to a fake weather API: a function shaped exactly like fetch() that waits a moment and then returns real Response objects filled with made-up data. Your app code can't tell the difference, and swapping in a real weather service later means changing one line.

You will build it in six stages. Each stage is complete and runnable, and the last one is the finished dashboard.

What you'll build

The finished dashboard:

  • loads the weather for a city as soon as it opens, with a pulsing placeholder while it waits;
  • shows the temperature, conditions, humidity, wind, the city's local time and a five-day forecast;
  • fetches the current conditions and the forecast in parallel;
  • shows a clear message and a Try again button when the server fails or the connection drops;
  • lets you search for a city or pick one from a row of buttons, and never shows stale results when you click quickly;
  • switches between metric and imperial units without asking the server again;
  • formats every number and date with Intl, so changing one locale string translates the formatting.

Along the way you will use async and await, Promises, Promise.all, fetch(), AbortController, Formatting with Intl and Creating and Removing Elements.

Step 1: The page and its styles

As in the to-do app, start with plain HTML and CSS so you can see the goal. Everything below is hard-coded. None of the buttons work yet.

Step 1: Markup and styles

A few choices to notice:

  • The humidity and wind figures use a description list (<dl>), because they are nameโ€“value pairs. See description lists.
  • The forecast is an ordered list, because the days have a meaningful order.
  • The big weather icon has aria-hidden="true". The words "Sunny" right below it already say the same thing, so screen readers don't need to announce the emoji too.

Step 2: A fake weather API

A real weather service would give you URLs like https://api.example.com/current?city=Lisbon. Our stand-in, fakeFetch(), accepts the same kind of URL and behaves like a server:

  • It waits 0.4โ€“1.4 seconds, a random delay, like a real network.
  • It answers /current and /forecast with JSON, using Response.json().
  • An unknown city gets a 404 with an error message in the body.
  • The city "Atlantis" gets a 503, so you can test a server failure.
  • The city "Offline" makes it throw a TypeError, which is what fetch() does when there is no connection at all.

The app talks to it through getJSON(), the small helper from the fetch() lesson: it checks response.ok and turns HTTP errors into thrown errors. Open the console under the preview to see the raw data.

Step 2: The fake API and getJSON()

Look at what the fake server sends. Temperatures are plain numbers in ยฐC, humidity is a fraction between 0 and 1, and times are ISO strings like "2026-10-14T13:53:00.000Z". Real APIs work the same way: they send raw values, and formatting them for people is the app's job. That job is step 3.

The fake server's wait() also accepts an AbortSignal. You won't need it until step 5, but the server is now finished, so you won't touch it again.

Using a real service. To switch to a real weather API, replace fakeFetch(url) in getJSON() with fetch(realUrl) and adapt the field names to that service's JSON. Most services need a free API key, and you should keep that key on your own server rather than in browser code that anyone can read.

Step 3: Rendering with Intl and Promise.all

Step 2 had two problems. The output was ugly, and the requests ran one after the other: the forecast request only started once the current conditions had arrived. The two requests don't depend on each other, so Promise.all() can start both at once. The total wait becomes the slower of the two instead of their sum.

For the display, the card is now a <template>. renderCard() clones it and fills each data-field slot with textContent, which is safe for any text the server sends. Every number and date goes through an Intl formatter:

Value from the API Formatter Shown as
21.4 (ยฐC) NumberFormat with style: "unit", unit: "celsius" 21ยฐC
14 (km/h) NumberFormat with unit: "kilometer-per-hour" 14 km/h
0.58 NumberFormat with style: "percent" 58%
"2026-10-15" DateTimeFormat with weekday: "short" Thu
"Europe/Lisbon" DateTimeFormat with timeZone 2:05 PM
updatedAt RelativeTimeFormat 12 minutes ago

Change LOCALE to "de-DE", "fr-FR" or "ja-JP" and run again: every number, weekday and phrase follows that language's rules.

Step 3: Parallel requests and Intl formatting

new URLSearchParams({ city }) builds the query string and encodes it, so a city such as "Sรฃo Paulo" or "Rock & Roll Town" arrives intact. Gluing "?city=" + city by hand would break on the &. See URLs, Location and History.

The formatters are created once, at the top. Building an Intl formatter does real work, such as loading locale rules, so make one and reuse it instead of creating a new one inside a loop.

Step 4: Loading and error states

So far the app shows "Loadingโ€ฆ" once and assumes success. A real app has to show three states clearly:

  • loading: a grey placeholder card in the shape of the real one, often called a skeleton;
  • error: a short message in plain words and a Try again button;
  • ready: the weather card.

This is the state-then-render pattern again. A state object holds status, the requested city, the data and the error message. render() draws whatever the state says, and showCity() changes the state at each point of the request: before it, after success and after failure.

getJSON() also gets smarter. When the server sends an error body like { "error": "โ€ฆ" }, it shows that message. When fakeFetch() throws, which means no connection, it throws a friendlier error and keeps the original as its cause. Use the new buttons to try every case, including Atlantis and Offline.

Step 4: Loading, error and ready states

Some details worth a second look:

  • try/catch around await is how async functions handle rejected promises. If either request in Promise.all() fails, the whole await throws, so one catch covers both.
  • response.json().catch(() => null) guards against error pages that aren't JSON, such as an HTML "502 Bad Gateway" page from a proxy.
  • The hidden status line with aria-live="polite" tells screen reader users what is happening ("Loadingโ€ฆ", "Showing the weather for Oslo.") without reading the whole card aloud each time.
  • The skeleton's pulse animation turns off for people who ask for less motion with prefers-reduced-motion.

Now try this: click Tokyo and then Oslo very quickly, several times. Because the delays are random, the Tokyo answer sometimes arrives after the Oslo one, and the dashboard shows Tokyo even though you asked for Oslo last. That bug is called a race condition, and step 5 fixes it.

Step 5: Search without race conditions

Step 5 adds the search form and fixes the race. The fix uses an AbortController:

  1. Before starting a new request, call abort() on the previous controller.
  2. Pass the new controller's signal through getJSON() to fakeFetch(), just as you would pass it to fetch(url, { signal }).
  3. An aborted request rejects with an error named "AbortError". showCity() ignores that error, because a newer request has already taken over.

A second check, if (signal.aborted) return, covers a rare edge case. A response can finish arriving at almost the same moment a new search starts. In that case nothing rejects, but the old result still must not win.

Step 5: Search and cancel stale requests

Click the city buttons quickly now. The console lists every request that was cancelled, and the card always shows the last city you picked. Type a city that isn't in the fake data, such as "Paris", and you get the server's own 404 message.

Cancelling also saves real resources. With a real fetch(), an aborted request stops downloading, so a user who clicks five cities doesn't make the phone download five forecasts.

Search as you type? If you later fetch on every key press, combine this with a debounce: wait until the user pauses for about 300 ms, then call showCity(). Debouncing reduces how many requests start, and the AbortController still protects you from slow, stale ones.

Step 6: Units and live "updated" times: the finished dashboard

The last stage adds two features that need no new requests:

  • ยฐC/ยฐF switch. The state stores raw metric values from the API, and a units setting picks how to display them. Each unit system has its own conversion functions and its own Intl formatters (celsius/fahrenheit, kilometer-per-hour/mile-per-hour). Switching units only changes state.units and calls render().
  • Live times. "Updated 12 minutes ago" and the local clock go stale while the page stays open. A setInterval() re-renders the card every 30 seconds while it is showing.
Step 6: The complete weather dashboard

The UNITS object is a lookup table. Each entry bundles everything one unit system needs: how to convert a value and how to format it. renderCard() receives one entry and never asks "metric or imperial?" itself. Adding a third system, such as Kelvin with meters per second, means adding one entry.

The timer calls render({ announce: false }) so that screen readers aren't told "Showing the weather for Lisbon" every 30 seconds. Updates you make on a schedule should stay silent. Only changes the user asked for should be announced.

Extension: remember the last city

A real dashboard would reopen on the city you looked at last. That's a job for localStorage. The sandbox blocks storage, so this can't run here, but in your own project it takes a few lines (see localStorage and sessionStorage):

JavaScript
const SETTINGS_KEY = "weather-settings";

function loadSettings() {
  try {
    return JSON.parse(localStorage.getItem(SETTINGS_KEY)) ?? {};
  } catch {
    return {}; // storage blocked or data corrupted
  }
}

function saveSettings() {
  try {
    localStorage.setItem(SETTINGS_KEY, JSON.stringify({ city: state.city, units: state.units }));
  } catch {
    // storage full or blocked: the app still works, it just forgets
  }
}

// On start-up, instead of showCity("Lisbon"):
const saved = loadSettings();
state.units = saved.units === "imperial" ? "imperial" : "metric";
showCity(saved.city || "Lisbon");
// ...and call saveSettings() at the end of render()

Notice that the saved units are checked before use. Stored data can be old, edited by hand or written by an earlier version of your app, so treat it like any other outside input.

More ideas to try

  • Make the default locale undefined and see the dashboard switch to your browser's language.
  • Show the forecast's first day as "tomorrow" with relativeFormat.format(1, "day").
  • Cache answers in a Map keyed by city for five minutes, so returning to a city shows instantly. See Maps.
  • Add a timeout with AbortSignal.any([controller.signal, AbortSignal.timeout(8000)]), and show "The server is taking too long" when it fires. Check browser support for AbortSignal.any() first; it is newer than AbortSignal.timeout().

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does loadWeather() use Promise.all() for the two requests?

    The requests don't depend on each other. Promise.all() starts both at once, and it rejects as soon as either one fails.
  2. 2. fetch() gets an HTTP 404 response. What happens?

    fetch() only rejects when no response arrives at all. A 404 is still a response, so getJSON() checks response.ok and throws its own error.
  3. 3. What problem does aborting the previous request in showCity() solve?

    Without cancellation, whichever response arrives last wins, even if it was requested first. That is a race condition.
  4. 4. Why does the app keep temperatures in ยฐC in its state and convert only when rendering?

    Raw data stays as the API sent it. The UNITS table converts and formats at display time, so the switch is instant.
  5. 5. Why are forecast dates formatted in the UTC time zone?

    In a time zone behind UTC, UTC midnight is still the previous evening, so formatting in local time could show the wrong day.

Summary

  • A fake API with the same shape as fetch() lets you build and test async code without a network. Swap in fetch() later, and nothing else changes.
  • Use async/await with try/catch, check response.ok, read error messages from the response body, and turn network failures into friendly messages.
  • Run independent requests in parallel with Promise.all().
  • Model the screen as explicit states (loading, error, ready) and render each one clearly, with a skeleton, a retry button and a polite live region.
  • Cancel outdated requests with AbortController to avoid race conditions, and ignore the resulting AbortError.
  • Keep raw values in state and format at display time with reusable Intl formatters for units, percentages, weekdays, time zones and relative times.

Next: Project: Expense Tracker, where forms, classes, reduce() and a CSS bar chart come together.