Skip to content

Weather Display App

Medium ~30 min

What you'll build

A weather app that fetches and displays weather data for a city. Shows a loading spinner while fetching, error message on failure, and weather details (temperature, conditions) on success.

Goals

  • Fetch data with useEffect and async/await
  • Manage loading, error, and data states
  • Handle the response and parse JSON
  • Clean up async operations on unmount

Prerequisites

  • useState and useEffect basics
  • Async/await and fetch API
  • Conditional rendering

Steps

  1. 1

    Set up state variables

    Create state for weather data, loading status, and error message.

    Code
    const [weather, setWeather] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    Expected result

    State is ready for the fetch lifecycle.

  2. 2

    Fetch weather data in useEffect

    Use useEffect with an async fetch call. Set loading to true before fetching, store the result, and handle errors with try/catch.

    Code
    useEffect(() => {
      let cancelled = false;
      async function fetchWeather() {
        try {
          const res = await fetch(`https://wttr.in/${city}?format=j1`);
          const data = await res.json();
          if (!cancelled) setWeather(data);
        } catch (err) {
          if (!cancelled) setError(err.message);
        } finally {
          if (!cancelled) setLoading(false);
        }
      }
      fetchWeather();
      return () => { cancelled = true; };
    }, [city]);

    Expected result

    Weather data is fetched on mount and when city changes.

  3. 3

    Render loading, error, and data states

    Use conditional rendering to show a spinner while loading, an error message on failure, and weather details on success.

    Code
    if (loading) return <div>Loading weather...</div>;
    if (error) return <div>Error: {error}</div>;
    return (
      <div>
        <h2>Weather for {city}</h2>
        <p>Temperature: {weather.current_condition[0].temp_C}°C</p>
      </div>
    );

    Expected result

    The app shows the appropriate state at each phase.

  4. 4

    Add state management & event handling

    Use useState to manage component state and add onClick/onChange handlers to interactive elements. State is the heart of React components, and event handling lets them respond to user actions.

    Code
    import { useState } from "react";
    
    export function MyComponent() {
      const [count, setCount] = useState(0);
      const [text, setText] = useState("");
    
      return (
        <div>
          <button onClick={() => setCount(c => c + 1)}>
            Count: {count}
          </button>
          <input
            value={text}
            onChange={(e) => setText(e.target.value)}
          />
        </div>
      );
    }

    Expected result

    Clicking the button increments the count; the input content updates in real time as you type.

  5. 5

    Add Props validation & component split

    Define a Props interface (TypeScript) or propTypes for the component, and split large components into smaller sub-components. Type-safe Props make the component interface clear and reusable.

    Code
    interface ChildProps {
      label: string;
      value: number;
      onChange: (v: number) => void;
    }
    
    function Child({ label, value, onChange }: ChildProps) {
      return (
        <label>
          {label}
          <input
            type="number"
            value={value}
            onChange={(e) => onChange(Number(e.target.value))}
          />
        </label>
      );
    }

    Expected result

    The child component receives type-safe Props; the parent can reuse it to render multiple fields.

Try it yourself

What you learned

You learned the data fetching pattern in React: use useEffect for the fetch, track loading/error/data states, and use a cleanup flag to prevent setting state on an unmounted component.

Related Resources

Related Lessons

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to topic