Skip to content
Tutorials Center
My learning

Topics

Lesson 74 of 87 ยท Projects

Project: Weather Dashboard

Build a Vue 3 weather dashboard against a mocked API: a status state machine, watch with stale-response protection, a useWeather composable and reusable cards with retry.

Almost every real application shows data that does not live in the browser: a weather forecast, a list of orders, a user profile. Fetching it looks easy, and then reality arrives. The request takes time, so you need a loading state. It can fail, so you need an error state and a retry button. The user can change their mind while a request is in flight, so old answers can overwrite new ones.

This project builds a small weather dashboard that handles all of those cases. The network is mocked: our own getWeather function waits a little and then returns data or fails. That keeps the lesson deterministic and works in the sandbox, which has no real API access. Swapping the mock for a real fetch later changes one function (fetching data covers the real thing). We will practise ref, watch, computed, props and composables.

The mocked API

The mock knows five cities, each with its own delay. Unknown cities fail, and "Flakyville" fails on the first call only, so you can practise retrying. All the examples below start with this same block:

JavaScript
const DATA = {
  oslo: { city: "Oslo", tempC: 4, condition: "Cloudy", humidity: 81, delay: 900 },
  cairo: { city: "Cairo", tempC: 31, condition: "Sunny", humidity: 22, delay: 200 },
  lima: { city: "Lima", tempC: 19, condition: "Fog", humidity: 88, delay: 400 },
  tokyo: { city: "Tokyo", tempC: 14, condition: "Rain", humidity: 70, delay: 500 },
  flakyville: { city: "Flakyville", tempC: 22, condition: "Windy", humidity: 55, delay: 300 },
};
const calls = {};

function getWeather(name) {
  const key = name.trim().toLowerCase();
  calls[key] = (calls[key] ?? 0) + 1;
  const entry = DATA[key];
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (!entry) {
        reject(new Error('No weather data for "' + name.trim() + '"'));
      } else if (key === "flakyville" && calls[key] === 1) {
        reject(new Error("Network error (simulated), try again"));
      } else {
        resolve({ city: entry.city, tempC: entry.tempC, condition: entry.condition, humidity: entry.humidity });
      }
    }, entry ? entry.delay : 300);
  });
}

A promise that resolves with data or rejects with an Error is exactly what fetch(...).then(r => r.json()) gives you, so the rest of the app will not care that it is fake.

Stage 1: one status instead of three booleans

The first instinct is loading, error and data refs updated separately. That allows impossible combinations (loading and error at the same time). A better model is a single status that is always exactly one of four values.

stateDiagram-v2
    [*] --> idle
    idle --> loading: load
    loading --> success: data arrives
    loading --> error: request fails
    success --> loading: reload
    error --> loading: retry

Four states, and every transition is named. The template simply shows one block per status.

Stage 1: loading, success and error

Try Atlantis (an error), then Flakyville (an error the first time and a success after "Retry"). The try/catch converts both failure modes into the same error status, and :disabled="status === 'loading'" stops double clicks while a request is in flight.

Stage 2: reload automatically with watch

Pressing a button is tedious. A dashboard should load when the city changes. That is a side effect reacting to state, which is exactly what watchers are for: watch(city, ...) with immediate: true also runs once at startup.

This introduces the classic bug. Suppose the user picks Oslo (slow, 900 ms) and then Cairo (fast, 200 ms). Cairo's answer arrives first, then Oslo's answer arrives and overwrites it. The selector says Cairo while the card shows Oslo.

sequenceDiagram
    participant U as User
    participant C as Component
    participant S as Server
    U->>C: choose Oslo
    C->>S: request Oslo (slow)
    U->>C: choose Cairo
    C->>S: request Cairo (fast)
    S-->>C: Cairo result
    S-->>C: Oslo result (late)
    Note over C: without a guard, Oslo overwrites Cairo

Responses can arrive in a different order than the requests were sent. The last response is not always the answer to the last question.

Vue's watcher gives its callback an onCleanup function. The cleanup you register runs before the next run of the callback (and when the watcher stops). We use it to mark the old request as stale, and every later step checks the flag. The checkbox lets you switch the protection off to see the bug for yourself, and the "Run the race" button reproduces it.

Stage 2: a watcher and the stale-response race

With the checkbox ticked, the race ends with Cairo on the card. Untick it and run the race again: after about a second the card flips to Oslo and the warning appears. The fix is tiny, but only because the watcher hands us a cleanup hook. A promise cannot be cancelled, so we do the next best thing and ignore its result. With a real fetch you can additionally cancel the request itself with an AbortController (fetching data).

Notice also that the mismatch warning is a computed value: it is derived from status, weather and city, never stored.

Stage 3: a composable and reusable cards

The watcher, the three refs and the cleanup trick form one idea: "load weather for a city". Wrap it in a composable so any component can use it. Two design rules from the composables lesson apply here:

  • Accept the input as a ref or a getter, and read it with toValue(). Then callers can pass () => props.city and the composable stays reactive.
  • Return refs, so the caller can destructure them without losing reactivity.

We also add a refresh function. Because the watcher already reacts to changes, refresh just bumps an attempt counter that the watcher lists as a second source.

Stage 3: useWeather and a dashboard of cards

What to notice:

  • Each card calls useWeather itself. The state is per card, so cards load in parallel and fail independently: Flakyville shows an error while Cairo shows data.
  • The unit switch is just a prop. temperature is a computed value, so changing the unit never refetches; the same tempC is converted on demand. The data you store should be the source data, and formatting belongs in computed values.
  • The composable knows nothing about cards. You could reuse it in a page header or in a test with a fake getWeather.
  • When a card is removed, Vue unmounts the component, and the watcher it created inside setup is stopped automatically. Watchers made synchronously in setup are tied to the component's lifetime, so there is nothing to clean up by hand (lifecycle hooks).

Moving to a real API

To use a real service you change only getWeather:

JavaScript
async function getWeather(name, signal) {
  const url = "https://api.example.com/weather?city=" + encodeURIComponent(name);
  const response = await fetch(url, { signal });
  if (!response.ok) {
    throw new Error("Server answered " + response.status);
  }
  return response.json();
}

Two habits are worth copying. fetch does not reject on a 404 or 500, so check response.ok and throw yourself. And always encodeURIComponent user text before it goes into a URL. You would also pass an AbortController signal from the cleanup function so the browser cancels outdated requests, and you would keep the key for the service out of client code (security).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is one status ref ('idle', 'loading', 'success', 'error') better than separate loading and error booleans?

    A single status can only hold one value, so impossible combinations cannot exist and the template simply shows one block per status.
  2. 2. The user selects Oslo (900 ms), then Cairo (200 ms). Without protection, what can go wrong?

    Responses can arrive in a different order than requests were sent. The callback must ignore results that belong to an outdated request.
  3. 3. When does the function registered with onCleanup inside a watch callback run?

    Vue calls the previous cleanup before the next invocation of the callback (and on stop or unmount). That is the perfect moment to mark the earlier request as stale or abort it.
  4. 4. Why does the unit switch not refetch the weather?

    The stored data is always Celsius. Formatting for Fahrenheit is derived in a computed property, so changing the prop recalculates it without any request.

Summary

  • Model loading as one status value and show one template block per status.
  • Use watch(source, callback, { immediate: true }) to load when inputs change, and onCleanup to ignore stale responses.
  • fetch does not reject on HTTP errors: check response.ok; encode user text in URLs.
  • Wrap the loading logic in a composable that accepts a ref or getter (toValue) and returns refs plus actions.
  • Store source data and derive display values (units, labels) with computed properties.
  • A mocked API makes behaviour deterministic for demos and tests; only one function changes when you go live.

Next: a project with lists, totals and animation, Project: Shopping Cart.