Skip to content
Tutorials Center
My learning

Topics

Lesson 110 of 132 ยท Projects

Project: Weather App

Build a weather app in React that handles loading, errors, retries and stale responses. Uses a clearly labelled fake API so every example runs in the browser sandbox.

A weather app is the classic "talk to an API" project. The interesting part is not drawing temperatures; it is everything that can go wrong between the user pressing Search and the data arriving: waiting, failing, a city that does not exist, and answers that come back in the wrong order.

Honesty note. The code sandbox cannot call real weather services or read your location, so these examples use a fake API (fakeWeatherApi) that waits a moment and returns made-up data. It has the same shape as a real fetch call: it returns a promise that resolves or rejects. Swapping in a real service later means replacing that one function. The location button is a stand-in too: browsers' geolocation is blocked in the sandbox.

We build in three stages: the request lifecycle, a search form with a status machine, and protection against stale responses. For background see data fetching and async patterns.

The plan

The request has four possible statuses: idle (nothing yet), loading, success and error. Store them as one status value instead of separate isLoading and isError booleans, which can contradict each other. The state is { status, data, error }.

Here is the fake API. It knows three cities, fails for one on purpose and treats everything else as "not found":

JavaScript
function fakeWeatherApi(city) {
  const db = {
    oslo: { city: 'Oslo', temp: -2, sky: 'Snow', wind: 14 },
    cairo: { city: 'Cairo', temp: 31, sky: 'Sunny', wind: 9 },
    lima: { city: 'Lima', temp: 19, sky: 'Cloudy', wind: 11 },
  };
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const key = city.trim().toLowerCase();
      if (key === 'error') reject(new Error('The weather service is down.'));
      else if (db[key]) resolve(db[key]);
      else reject(new Error('No city called "' + city.trim() + '" was found.'));
    }, 600);
  });
}

Stage 1: load once with an effect

Stage 1: loading, success, error

Notice how the JSX is just three early returns, one per status. Each status has exactly one screen, so you cannot show a spinner and an error together.

Stage 2: a search form with retry

Now the user types the city. The form is a controlled input, and a search function runs on submit. Because the request is the result of a user action, not of rendering, it belongs in an event handler, not an effect (you might not need an effect). We also add a Retry button and a small history of recent cities.

Stage 2: search form

Disabling Search while loading prevents double submissions, and aria-live="polite" makes screen readers announce each status change (accessibility).

Stage 3: ignore stale responses

Suppose the user searches "Oslo", then quickly "Cairo". If Oslo's answer arrives after Cairo's, the screen shows Oslo even though the user last asked for Cairo. This is a race condition. The usual fix is to remember which request is the latest, and ignore any other. We do it with a ref holding a counter. (For an effect-based fetch the same idea is a cleanup flag, see effect cleanup.)

To make the bug visible, the fake API below is deliberately slower for Oslo than for Cairo. Press "Oslo" and then "Cairo" quickly.

Stage 3: race condition guard

After about a second the unguarded panel shows Oslo, which is wrong since Cairo was requested last. The guarded panel keeps Cairo. In real apps you would also cancel the network request with an AbortController, and libraries such as TanStack Query handle all of this for you.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why use one status value ('idle', 'loading', 'success', 'error') instead of separate isLoading and isError booleans?

    With one status the screen is in exactly one situation at a time, and each situation maps to one branch of JSX.
  2. 2. Where should a request triggered by pressing Search be made?

    Effects are for synchronising with something because of what is rendered. A click or submit is an event, so its work belongs in the handler.
  3. 3. What goes wrong if the user searches twice and responses arrive out of order?

    Network replies can arrive in any order. Track the latest request id (or abort the old request) and ignore the others.
  4. 4. Why does this lesson's fake API exist?

    The fake function has the same contract as fetch (a promise that resolves or rejects), so the component code is unchanged when a real call replaces it.

Summary

  • Model a request as one status: idle, loading, success or error, and render one screen per status.
  • Trigger requests from event handlers when they are caused by user actions; use effects when the request depends on rendered values.
  • Always provide loading feedback, a readable error and a retry path.
  • Guard against races with a latest-request ref (or AbortController) so old responses cannot overwrite new ones.
  • Wrap the network in one small function so a fake can be swapped for the real service.

Next: Project: Memory Card Game