CodingNic

Units & Preferences

Update Weather Display

Units & Preferences 10 min read

Update Weather Display

Task

Refetch the weather when the unit changes so API values and labels stay aligned.

File / section

src/App.jsx — add toggleUnit

Change

Create const next = unit === "metric" ? "imperial" : "metric"; setUnit(next);. If weather exists, build a coordinate request with units: next and call loadWeather(...).

Why this change matters

The request must use the next unit, not the stale current unit value.

Test it

Search a city, click the unit button, and confirm the loader briefly appears while the data refreshes.

Checkpoint

Changing units updates the dashboard from fresh API data.

javascript
const toggleUnit = () => {
  const next = unit === "metric" ? "imperial" : "metric";
  setUnit(next);

  if (weather) {
    const params = new URLSearchParams({
      lat: weather.coord.lat,
      lon: weather.coord.lon,
      appid: API_KEY,
      units: next
    });
    loadWeather(`${API_BASE}/weather?${params}`);
  }
};