CodingNic

Temperature Units & Persistent Preferences

Reload the Current Location on Toggle

Temperature Units & Persistent Preferences 25 min read

Reload the Current Location on Toggle

Reload the Current Location on Toggle

Task

After weather has loaded, changing units should reload the same place automatically.

Open

Replace the unit listener with this version.

Implementation

javascript
$("unitToggle").addEventListener("click", async () => {
  state.unit = state.unit === "metric" ? "imperial" : "metric";
  localStorage.setItem("weatherUnit", state.unit);
  $("unitToggle").textContent = state.unit === "metric" ? "°C" : "°F";

  if (state.lastData) {
    await fetchByCoordinates(
      state.lastData.coord.lat,
      state.lastData.coord.lon
    );
  }
});

displayCurrent() stores the latest response in state.lastData. Its coord property provides a stable location, so the toggle can request the same place with a different unit system instead of asking the learner to search again.

Test

Search for a city, wait for the weather, then click the unit toggle. The city name should remain unchanged while temperatures and wind units change.

Expected result

Unit switching preserves the current location and refreshes its data.

Checkpoint

Before moving on, confirm the expected result in the running app and make sure the browser console has no blocking errors.