Building React Apps: Weather, Music and Video · Course book
Chapter 1: A Weather App from an API
A weather app is the classic first project for working with real data from an API. It is small enough to finish in an afternoon, yet it touches every essential skill of a modern front-end developer: splitting a screen into React components, keeping data in state, fetching from a third-party service, handling loading and errors, converting units and times, and presenting numbers in a clear, attractive way. This chapter explains how such an app is built with React and the OpenWeather API, from planning the interface and protecting the API key to fetching current conditions and a forecast, turning raw values into readable ones and summarising a day of three-hourly forecasts, all worked through by hand.
Planning the app and its components
A weather app usually has four parts: a search box where the user types a city, a current weather card with the temperature, an icon, a description and details such as humidity and wind, a forecast showing the next hours or days, and messages for loading and errors. In React each part becomes a component, a function that returns the markup for that part of the screen. The top-level App component holds the shared data and passes it down to the others as props.
Project tooling such as Vite creates a React project in seconds with a fast development server. Styling can use plain CSS or a utility framework; either way, design for a phone-sized screen first, since many people check the weather on their phones, then widen the layout for larger screens.
The data the app needs flows in one direction. The search box reports the city the user submitted; App fetches the weather for it and stores the result in state; React then re-renders the cards with the new data. Keeping the fetching in one place, rather than in every card, makes the app easier to reason about and avoids requesting the same data twice.
The search box is a controlled input: its value lives in state, updated on every keystroke by an onChange handler, and the surrounding <form> calls a handler on submit, which first calls event.preventDefault() so the browser does not reload the page. Wrapping the input in a form, rather than listening for clicks on a button, means pressing Enter on a phone keyboard or a desktop works automatically. The handler trims the text and ignores empty searches before asking App to fetch. Components such as the current weather card then receive exactly the values they need, for example <CurrentWeather data={weather} unit={unit} />, and contain no fetching logic of their own, which makes them simple to test and reuse.
The OpenWeather API and the API key
OpenWeather provides weather data over HTTP. Two endpoints cover most needs: the current weather endpoint, which returns conditions now for a city or a pair of coordinates, and the 5 day / 3 hour forecast endpoint, which returns a list of forecasts at three-hour intervals, eight per day and forty in total. Every request includes an API key, a code that identifies your account, obtained by signing up.
| Field in the response | Meaning | Shown as |
|---|---|---|
main.temp | Temperature, in kelvin unless another unit is requested | 20°C |
main.humidity | Relative humidity in percent | Humidity 64% |
wind.speed | Wind speed, metres per second in metric units | Wind 4.1 m/s |
weather[0].description and icon | Text description and an icon code | "light rain" with a matching picture |
dt and timezone | Time as a Unix timestamp, and the city's offset from UTC in seconds | Tuesday 23:13 |
In a Vite project, the key is placed in a .env file as a variable whose name starts with VITE_, read in code as import.meta.env.VITE_WEATHER_KEY, and the .env file is listed in .gitignore so it is never committed. Be aware that anything sent to the browser can be seen by a determined user. For a learning project with a free key that is acceptable; a production app would send requests through its own small server, which adds the key and can also cache results to stay within the API's usage limits.
Fetching data with state and effects
React's useState hook stores the weather data, a loading flag and an error message. Fetching happens when the user submits a search, or on first load for a default city inside useEffect. The function sets loading to true, requests the data, checks the response, stores the result and finally sets loading to false.
async function loadWeather(city) {
setLoading(true);
setError("");
try {
const url = `${BASE}/weather?q=${encodeURIComponent(city)}&units=metric&appid=${KEY}`;
const res = await fetch(url);
if (!res.ok) throw new Error(res.status === 404 ? "City not found" : "Weather service error");
setWeather(await res.json());
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
}
Several details matter. encodeURIComponent makes city names with spaces or accents safe to put in a URL. The fetch function does not throw for HTTP errors such as 404, so the code checks res.ok itself and produces a friendly message. While loading, the cards can show a spinner or a skeleton; when there is an error, a clear message with the option to try again replaces them. Disabling the search button while a request is running prevents duplicate requests.
A convenient extra is "use my location": the browser's geolocation API asks the user's permission and, if granted, provides latitude and longitude, which can be sent to the same endpoints instead of a city name. If permission is refused, the app should simply fall back to the search box.
Units, times and summarising the forecast
Raw API values need converting before people can read them. Temperatures default to kelvin: subtract 273.15 for Celsius, so 293.15 K is 20°C, and multiply Celsius by 9/5 and add 32 for Fahrenheit, so 20°C is 68°F. Requesting units=metric or units=imperial asks the API to do the conversion; a unit toggle in the app can either refetch or convert values already received.
Times arrive as Unix timestamps, seconds since 1 January 1970 in UTC. To show the city's local time, add the city's timezone offset in seconds and format the result as UTC. For example, the timestamp 1,700,000,000 is 22:13:20 UTC on 14 November 2023; for a city one hour ahead of UTC, with an offset of 3,600, it is 23:13:20 local time.
Formatting matters as much as calculation. Rounding temperatures to whole degrees, showing day names rather than dates, using the browser's Intl.DateTimeFormat for times in the user's language and choosing icons and background colours that match the conditions all make the app feel finished.
Finishing touches and deployment
A production-ready weather app remembers the last city searched, for example in localStorage, so it opens with useful information. It avoids requesting new data on every keystroke by fetching only when the form is submitted, or by waiting until the user stops typing for a moment, a technique called debouncing. Accessible markup, with a labelled input, a real submit button and text alternatives for weather icons, makes the app usable for everyone.
Small visual touches make a big difference. The icon code from the API can select a matching background, a warm gradient for clear days and cooler tones for rain or snow, and the wind direction, given in degrees, can rotate a small arrow with a CSS transform. Before publishing, try the awkward cases on purpose: a misspelt city, a city name shared by several countries, a slow connection simulated in the browser's developer tools, and a very narrow screen. Each one usually reveals a message or layout that needs improving.
Because the app is a static bundle of HTML, CSS and JavaScript, it can be built with npm run build and deployed to any static host. Remember to set the API key as an environment variable in the hosting service's settings, since the .env file is not uploaded with the code. Rebuild after changing it, because Vite inserts the value when the bundle is built.
Practice tasks
- Convert 281.15 K to Celsius and Fahrenheit.
- A reading has timestamp 1,700,003,600 and the city's offset is −18,000 seconds. What is the local time?
- Tomorrow's eight readings are 6, 5, 5, 9, 13, 14, 11 and 8°C. Give the low, the high and the average.
- Write the condition that shows "City not found" only for a 404 response, and a general message otherwise.
- Explain why the API key in a browser app is not truly secret, and how a small server would fix that.
- Describe how you would group the forty forecast readings into five daily summaries.
This course book is available to read online only at tech-academy.chrysolites.org.