Thuta Learning
JavaScript
ProjectsProgrammingBeginner

Weather App

JavaScriptLesson 4740 min

What you'll walk away with

  • Put a typed city into a URL safely with encodeURIComponent()
  • Explain why fetch() does not reject on 404 or 500, and check res.ok
  • Turn a nested API response into a UI view model with destructuring
  • Accept fetch as a parameter so the logic can be tested without a network
  • Describe how AbortController cancels a search that has become obsolete

Explain it simply

Explain it simply

A Weather App sends a question to an outside service and shows the answer in a form people can read. The user types "Yangon". The app sends a request to a weather API and waits for a JSON reply. When the reply arrives, it puts the temperature, the cloud conditions and the wind speed on the screen.

It is like ordering from a waiter in a restaurant. While the waiter checks with the kitchen, you wait. Sometimes the answer that comes back is "we do not have that dish". A good app handles all three moments: the waiting, the answer, and the missing answer.

Problem → Why → Solution

The problem: the first draft only works in the demo

The code below is the first version many tutorials show. You try "Yangon", a temperature appears, and it feels finished. But when a user types a city that does not exist, the server replies with a 404 and { message: "city not found" }. data.main is undefined, so data.main.temp throws a TypeError and the screen simply stops changing.

There are three more problems. A city name containing & or # breaks the URL. API_KEY sits in JavaScript that the browser downloads, so anyone who opens DevTools can copy it. And if the user searches twice quickly, the slower first response can arrive last and overwrite the newer result.

weather-draft.js
const API_KEY = "abc123-secret"; // shipped to every visitor's browser

async function onSearch() {
  const city = document.querySelector("#city").value; // "Ho Chi Minh & co" breaks the URL
  const res = await fetch(`https://api.example.com/weather?q=${city}&key=${API_KEY}`);
  const data = await res.json(); // runs even when the server answered 404 or 500
  document.querySelector("#temp").textContent = data.main.temp + "°";
}

Why does it fail without a clear error?

The promise from fetch() only rejects when the network itself fails. A 404 or a 500 is still "a response arrived" as far as fetch is concerned. Unless you check res.ok yourself, the error body is treated as weather data, and the failure surfaces later as a confusing TypeError somewhere else.

Core concept: split one request into five stages

When an app calls an API, putting all the code inside one click handler means every test needs a browser, a network and an API key. In this project we split the work into five stages and give each stage its own small function. Only the last stage touches the DOM.

1. Validate and encode the input

Trim the spaces and stop before any request if nothing is left. Wrap the rest in encodeURIComponent(), so accented names like "São Paulo" and symbols like & travel as a value instead of becoming part of the URL's structure.

2. Send the request

getWeather() receives the fetch function as a parameter. In the browser you pass the real fetch; in a test you pass a fake one. This technique is called dependency injection.

3. Check the status

res.ok is true only for statuses 200 to 299. Otherwise throw an Error with a message the user understands: a 404 means the city was not found, while a 429 means "too many requests, try again shortly".

4. Transform into a view model

Turn the API's nested JSON into the flat object the UI needs. Do unit conversion (m/s to km/h) and rounding here, in one place. If the API renames a field, this is the only function you edit.

5. Render

The UI layer shows a loading state, awaits getWeather(), and then displays either the view model or err.message.

StageNeeds the DOM?Testable in Node?
buildUrl / toViewModelNoYes (pure functions)
getWeatherNoYes (with a fake fetch)
Form handlerYesOnly in a browser

On the UI side, the screen is always in exactly one of four states: idle before any search, loading while waiting, success with data, or error with a message. Designing all four up front prevents bugs such as a loading spinner that never disappears.

Mental model: check, send, check, shape, show
  1. Trim and encode the city
  2. Send it with the injected fetch
  3. Throw unless res.ok
  4. Reshape JSON into a view model
  5. Show loading, data or error

Stages 1 to 4 are plain JavaScript with no DOM, so most bugs can be found without opening a browser at all.

General pattern

javascript
async function getResource(input, fetchFn = fetch) {
  if (!isValid(input)) throw new Error("Explain what the user must fix");
  const res = await fetchFn(buildUrl(input)); // encode every user value
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return toViewModel(await res.json()); // raw API shape -> what the UI needs
}

// UI layer: show "Loading...", then render the view model or err.message

Every API-calling function follows this shape: validate the input, send an encoded URL, check the status before parsing JSON, and return the UI's shape. Taking fetchFn as a parameter lets a test swap it out.

Run the weather logic against a fake API

This file never touches the network. fakeFetch() returns an object with ok, status and json(), just like a real fetch response, so getWeather() cannot tell the difference. main() tries four inputs: a normal name, a name with stray spaces and lower case, a city the API does not know, and input that is only spaces.

weather.js
// weather.js - the logic of the app. The page only calls these functions.
const fakeResponses = {
  yangon: { name: "Yangon", main: { temp: 32.4, humidity: 70 },
    weather: [{ main: "Clouds" }], wind: { speed: 4.2 } },
  mandalay: { name: "Mandalay", main: { temp: 35.1, humidity: 50 },
    weather: [{ main: "Clear" }], wind: { speed: 2.8 } },
};

// Stand-in for fetch(): same shape (ok, status, json()), no network needed.
async function fakeFetch(url) {
  const city = new URL(url).searchParams.get("q").toLowerCase();
  const body = fakeResponses[city];
  return {
    ok: body !== undefined,
    status: body ? 200 : 404,
    json: async () => body ?? { message: "city not found" },
  };
}

function buildUrl(city) {
  const q = encodeURIComponent(city.trim());
  return `https://api.example.com/weather?q=${q}&units=metric`;
}

const toFahrenheit = (c) => Math.round((c * 9) / 5 + 32);

function toViewModel(data) {
  const { name, main: { temp, humidity }, weather: [first], wind } = data;
  return {
    city: name,
    tempC: Math.round(temp),
    tempF: toFahrenheit(temp),
    condition: first.main,
    humidity,
    windKmh: Math.round(wind.speed * 3.6), // m/s -> km/h
  };
}

async function getWeather(city, fetchFn = fakeFetch) {
  if (!city.trim()) throw new Error("Please type a city name");
  const res = await fetchFn(buildUrl(city));
  if (!res.ok) {
    const notFound = `No data for "${city.trim()}"`;
    throw new Error(res.status === 404 ? notFound : `HTTP ${res.status}`);
  }
  return toViewModel(await res.json());
}

function formatWeather(w) {
  return `${w.city}: ${w.tempC}°C / ${w.tempF}°F, ${w.condition}, ` +
    `humidity ${w.humidity}%, wind ${w.windKmh} km/h`;
}

async function main() {
  for (const city of ["Yangon", "  mandalay ", "Tokyo", "   "]) {
    try {
      console.log(formatWeather(await getWeather(city)));
    } catch (err) {
      console.log(`Error: ${err.message}`);
    }
  }
}

main();

Code breakdown

  1. Encode the user's textconst q = encodeURIComponent(city.trim());

    The spaces are trimmed first, then encoded. " mandalay " becomes q=mandalay, and a name containing & becomes %26, so the URL stays intact.

  2. A fake with the real shapeasync function fakeFetch(url) {

    The fake is async and returns { ok, status, json }. As long as it matches the real fetch's shape, getWeather() works with either one unchanged.

  3. Check the status before parsingif (!res.ok) {

    For Tokyo the fake answers 404. This check means the error body is never mistaken for weather; instead the function throws with the clear message No data for "Tokyo".

  4. Nested destructuringconst { name, main: { temp, humidity }, weather: [first], wind } = data;

    It pulls temp and humidity straight out of main and puts the first element of the weather array into first. This single line documents which parts of the API shape the app depends on.

  5. Unit conversion in one placewindKmh: Math.round(wind.speed * 3.6), // m/s -> km/h

    4.2 m/s × 3.6 is 15.12, shown as 15 km/h. Fahrenheit is also computed from the unrounded 32.4, giving 90.32, which rounds to 90.

  6. Default to the fake, accept the real oneasync function getWeather(city, fetchFn = fakeFetch) {

    The default parameter uses the fake in this demo, while the browser can call getWeather(city, fetch) to pass the real one.

You should see
Yangon: 32°C / 90°F, Clouds, humidity 70%, wind 15 km/h
Mandalay: 35°C / 95°F, Clear, humidity 50%, wind 10 km/h
Error: No data for "Tokyo"
Error: Please type a city name
What happens on one search
  1. Trim the city and check it is not empty
  2. Build the URL with encodeURIComponent()
  3. Await fetchFn(url)
  4. Check res.ok
  5. Reshape the JSON and display it

Status 200-299

Yangon: 32°C / 90°F, Clouds, ...

404 or empty input

Error: No data for "Tokyo"

Wiring the page and hiding the API key

In the browser, the form handler only calls into the logic file. Each new search first calls abort() on the previous AbortController, so a slow old request can no longer overwrite a newer result. An aborted fetch rejects with an AbortError, and that particular error is not shown to the user.

Notice that the URL carries no key. In production the browser calls your own server at /api/weather, and the server adds the key before forwarding the request to the provider. This arrangement is called a proxy.

ui.js
// ui.js - browser only: connects the form to getWeather() and formatWeather()
const form = document.querySelector("#search");
const output = document.querySelector("#result");
let controller = null;

form.addEventListener("submit", async (event) => {
  event.preventDefault();
  controller?.abort(); // the previous search is now obsolete
  controller = new AbortController();
  const signal = controller.signal;
  output.textContent = "Loading...";
  try {
    const city = new FormData(form).get("city");
    const weather = await getWeather(city, (url) => fetch(url, { signal }));
    output.textContent = formatWeather(weather);
  } catch (err) {
    if (err.name !== "AbortError") output.textContent = err.message;
  }
});

In real projects

In real projects

Real weather providers usually limit free plans to a certain number of requests per minute or per day. That is why apps send a request on submit instead of on every keystroke, or debounce typing so the request goes out only after the user pauses for about 300ms. A 429 status gets its own message: "too many requests, try again shortly".

Label units and times as well. Make it clear whether a number is °C or °F, and whether "3 PM" is in the user's timezone or the city's. Weather barely changes within a few minutes, so caching each city's result for about ten minutes saves API quota and makes the app feel faster. In this lesson's challenge you build exactly that cache.

Common mistakes

Common mistakes

Expecting fetch to throw on a 404

Wrapping fetch in try/catch feels like it catches every error. In reality the catch block only sees network failures such as being offline or a DNS lookup failing. To handle 404 and 500 you must write if (!res.ok) throw ... yourself.

Gluing user text straight into the URL

Writing `?q=${city}` turns "Rock & Roll Town" into q=Rock plus a separate parameter named " Roll Town". Wrap every query value in encodeURIComponent(), or build the query with URLSearchParams.

Trusting the response shape blindly

If the API returns an empty weather array, first is undefined and first.main crashes. Check the fields you rely on inside toViewModel() and throw an error such as "Unexpected data from server" when they are missing.

Never ship a secret key in frontend code

Even a value placed in a build tool's environment variable is public once it ends up in the browser bundle. If the provider treats the key as secret, call the API through a server proxy.

Mini challenge

A weather client with a ten-minute cache

Write a createWeatherClient() factory. Asking for the same city again within ten minutes must return the cached result without touching the network. Inject a fake fetch and a fake clock, and check how many network calls happen.

  • " YANGON " and "yangon" must share one cache key
  • A result served from the cache carries cached: true
  • Once ttlMs has passed, the client asks the network again
  • Failed responses (such as a 404) are never cached
weather-cache.js
const TEN_MINUTES = 10 * 60 * 1000;

function normalizeCity(city) {
  // TODO: trim spaces and lower-case, so " Yangon" and "yangon" share a key
}

function createWeatherClient(fetchFn, now = () => Date.now(), ttlMs = TEN_MINUTES) {
  const cache = new Map(); // key -> { data, savedAt }

  async function getWeather(city) {
    // TODO: reject an empty city with a clear Error
    // TODO: return a fresh cache entry with cached: true (no network call)
    // TODO: otherwise call fetchFn, throw on !res.ok, store the data + now()
    // TODO: return the data with cached: false
  }

  return { getWeather };
}

// TODO: test with a fake fetch that counts calls and a fake clock you can move

Expected: The first Yangon shows calls=1, " YANGON " shows cached=true with calls still 1, eleven minutes later calls=2, and asking for Atlantis twice gives two 404 errors with calls=3 and then calls=4.

Show hint

Call the now() parameter instead of Date.now() directly. In the test, keep let clock = 0 and simply add to clock to jump eleven minutes ahead. Store savedAt with each cache entry and test now() - savedAt < ttlMs.

Show solution
weather-cache.js
const TEN_MINUTES = 10 * 60 * 1000;

function normalizeCity(city) {
  return city.trim().toLowerCase();
}

function createWeatherClient(fetchFn, now = () => Date.now(), ttlMs = TEN_MINUTES) {
  const cache = new Map(); // key -> { data, savedAt }

  async function getWeather(city) {
    const key = normalizeCity(city);
    if (!key) throw new Error("Please type a city name");
    const hit = cache.get(key);
    if (hit && now() - hit.savedAt < ttlMs) return { ...hit.data, cached: true };

    const res = await fetchFn(`/api/weather?q=${encodeURIComponent(key)}`);
    if (!res.ok) throw new Error(`HTTP ${res.status} for "${key}"`);
    const data = await res.json();
    cache.set(key, { data, savedAt: now() });
    return { ...data, cached: false };
  }

  return { getWeather };
}

// --- test bench: a fake network and a fake clock ---
let networkCalls = 0;
async function fakeFetch(url) {
  networkCalls++;
  const city = decodeURIComponent(url.split("q=")[1]);
  const temps = { yangon: 32, mandalay: 35 };
  const found = city in temps;
  return {
    ok: found,
    status: found ? 200 : 404,
    json: async () => ({ city, tempC: temps[city] }),
  };
}

let clock = 0;
const client = createWeatherClient(fakeFetch, () => clock);

async function show(city) {
  try {
    const w = await client.getWeather(city);
    console.log(`${w.city} ${w.tempC}°C cached=${w.cached} calls=${networkCalls}`);
  } catch (err) {
    console.log(`Error: ${err.message} calls=${networkCalls}`);
  }
}

await show("Yangon");
await show("  YANGON ");     // same key, served from cache
clock += 11 * 60 * 1000;     // 11 minutes later: entry expired
await show("yangon");
await show("Atlantis");      // errors are not cached...
await show("Atlantis");      // ...so this asks the network again

Quick quiz 1 / 3

The server answers with status 404. What happens at `const res = await fetch(url)`?

Quick quiz 2 / 3

If buildUrl("Rock & Roll") skipped encodeURIComponent(), what would the server read as q?

Quick quiz 3 / 3

What is the main benefit of getWeather() taking the fetch function as a parameter (fetchFn)?

What to remember

  • Split a weather request into stages: validate, send, check status, reshape, show
  • fetch does not reject on 404 or 500, so always check res.ok
  • Put user-typed values into URLs through encodeURIComponent()
  • Injecting fetch lets you test the logic in Node with fake data
  • Keep secret keys behind a proxy and cancel obsolete searches with AbortController

MDN — Fetch API — MDN Web Docs

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Weather App | Thuta Learning