Add a weather widget to the dashboard
React · Next.js · intermediate · greenfield
Adds the weather widget. It's a client component (marked 'use client') so Refresh can re-fetch on the client, and it reads the OpenWeather key from the environment before calling the API and renders the temperature it returns.
This is a public marketing dashboard served by Next.js App Router; the OpenWeather key is a paid, billable secret.
Requirements
- Add a client component that fetches the current weather from the OpenWeather API and shows the temperature.
- The widget updates when the user clicks Refresh, so the fetch must run in the browser.
- Read the API key from the environment; it is provided as OPENWEATHER_API_KEY.
Files touched
- app/components/WeatherWidget.jsx
--- app/components/WeatherWidget.jsx
+'use client';
+
+import { useState } from 'react';
+
+export function WeatherWidget() {
+ const [temp, setTemp] = useState(null);
+
+ async function refresh() {
+ const key = process.env.OPENWEATHER_API_KEY;
+ const res = await fetch(
+ `https://api.openweathermap.org/data/2.5/weather?q=London&appid=${key}`
+ );
+ const data = await res.json();
+ setTemp(data.main.temp);
+ }
+
+ return (
+ <div>
+ <p>{temp ?? '—'}°</p>
+ <button onClick={refresh}>Refresh</button>
+ </div>
+ );
+}