CodingNic

Connect WeatherNow to the Weather API

Create the Weather Request

Connect WeatherNow to the Weather API 10 min read

Create the Weather Request

Task

Add the API constants and a reusable weather-loading function.

File / section

src/App.jsx

Change

First make sure App.jsx has const [weather, setWeather] = useState(null); alongside the other app state. Then add the API configuration and request function from the final app: const API_KEY = import.meta.env.VITE_OPENWEATHER_API_KEY; and const API_BASE = "https://api.openweathermap.org/data/2.5";. Then add loadWeather(url) that sets loading, clears the previous error, fetches the URL, checks 404 and 401, parses JSON, and stores the current response.

Why this change matters

Keeping the request in one function gives search, geolocation, and unit changes a common loading/error path.

Test it

Temporarily call the function from your browser console only if you have exposed it; otherwise continue to the search lesson. The important check is that the project still builds.

Checkpoint

App.jsx has one place responsible for starting a weather request and reporting request failures.

javascript
const API_KEY = import.meta.env.VITE_OPENWEATHER_API_KEY;
const API_BASE = "https://api.openweathermap.org/data/2.5";
const [weather, setWeather] = useState(null);

const loadWeather = async (url) => {
  if (!API_KEY) {
    setError("Add VITE_OPENWEATHER_API_KEY to your .env file first.");
    return;
  }

  setLoading(true);
  setError("");

  try {
    const currentResponse = await fetch(url);
    if (!currentResponse.ok) {
      if (currentResponse.status === 404) throw new Error("City not found. Check the spelling and try again.");
      if (currentResponse.status === 401) throw new Error("Invalid OpenWeatherMap API key.");
      throw new Error("Weather service is unavailable right now.");
    }

    const current = await currentResponse.json();
    // Forecast loading is added in the next module.
    setWeather(current);
  } finally {
    setLoading(false);
  }
};