javascriptintermediate10 minutes

Build a Weather Dashboard with Dynamic City Search

Create a small weather dashboard application in JavaScript that fetches and displays weather data for cities searched by the user, using a public weather API.

Challenge prompt

Build a weather dashboard function in JavaScript that accepts a city name as input, fetches current weather data from a public API (like OpenWeatherMap), and returns an object containing the city name, temperature (in Celsius), weather condition description, and an icon URL. Ensure your function handles errors gracefully for invalid city names or API issues. Structure your code to allow easy extension for additional features like a 5-day forecast in the future.

Guidance

  • Use fetch() to call the weather API asynchronously and parse the JSON response.
  • Extract the relevant data fields: city name, temperature in Celsius, weather description, and icon code.
  • Convert temperature from Kelvin to Celsius if necessary.
  • Implement basic error handling for invalid inputs or network errors.

Hints

  • OpenWeatherMap API's current weather endpoint is https://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_key}.
  • You can convert temperature: Celsius = Kelvin - 273.15.
  • Check if the API response includes a 'cod' field that signals an error when the city is invalid.

Starter code

async function getWeatherForCity(city) {
  const apiKey = 'YOUR_API_KEY';
  // Your code here
}

Expected output

getWeatherForCity('London') should return an object like: { city: 'London', temperature: 15.0, // degrees Celsius description: 'light rain', iconUrl: 'http://openweathermap.org/img/wn/10d@2x.png' }

Core concepts

API consumptionasynchronous JavaScripterror handlingdata transformation

Challenge a Friend

Send this duel to someone else and see if they can solve it.