☁️ Day 40 — Mini Project: Weather Dashboard using API
Hi Guys Welcome to Day 40 ⛅ You’ve learned Fetch, JSON, and Web Storage — let’s combine them to create a Weather Dashboard. This real-world project teaches how to fetch data from an API, handle user input, and store city preferences.
🧱 1️⃣ Project Overview
Our app will:
- Fetch real-time weather data using the OpenWeatherMap API.
- Display temperature, humidity, and weather conditions.
- Store last searched city in localStorage.
📄 2️⃣ Basic HTML Structure
<div id="weatherApp"> <h2>🌤 Weather Dashboard</h2> <input id="cityInput" placeholder="Enter city..." /> <button id="searchBtn">Search</button> <div id="result"></div> </div>
🎨 3️⃣ Simple Styling
body { font-family: Poppins, sans-serif; background:#e1f5fe; padding:20px; }
#weatherApp { max-width:400px; margin:auto; background:#fff; padding:20px; border-radius:12px; box-shadow:0 4px 16px rgba(0,0,0,0.1); }
input { width:70%; padding:8px; border:1px solid #ccc; border-radius:6px; }
button { padding:8px 12px; border:none; background:#0277bd; color:white; border-radius:6px; cursor:pointer; }
#result { margin-top:20px; font-size:16px; }
⚙️ 4️⃣ JavaScript Logic
We’ll use fetch() to call the OpenWeather API, handle responses, and update the DOM dynamically.
const apiKey = "YOUR_API_KEY_HERE";
const cityInput = document.getElementById("cityInput");
const searchBtn = document.getElementById("searchBtn");
const result = document.getElementById("result");
const lastCity = localStorage.getItem("city");
if(lastCity) fetchWeather(lastCity);
searchBtn.addEventListener("click", ()=>{
const city = cityInput.value.trim();
if(city) {
fetchWeather(city);
localStorage.setItem("city", city);
}
});
async function fetchWeather(city){
try {
result.innerHTML = "Fetching...";
const res = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`);
if(!res.ok) throw new Error("City not found!");
const data = await res.json();
showWeather(data);
} catch(err) {
result.innerHTML = `${err.message}`;
}
}
function showWeather(data){
result.innerHTML = `
<h3>${data.name}, ${data.sys.country}</h3>
<p>🌡 Temp: ${data.main.temp}°C</p>
<p>💧 Humidity: ${data.main.humidity}%</p>
<p>🌬 Wind: ${data.wind.speed} m/s</p>
`;
}
You can get a free API key from OpenWeatherMap.org.
🧩 5️⃣ Add Persistence
We save the last searched city in localStorage so it loads automatically next time.
💡 6️⃣ Extra Challenges
- Show an icon for weather conditions.
- Add temperature in Fahrenheit (toggle mode).
- Use sessionStorage for “Recent Search” history.
🎯 Summary
You’ve built a real working mini-app that fetches data from the web and stores preferences locally! This project teaches the complete workflow: API calls → JSON parsing → DOM updates → data persistence. Next, you’ll explore form validation and event delegation — the backbone of user interaction.
Comments
Post a Comment