ProjectsReactAPIFrontendBeginner

Build a Weather App with React and OpenWeather API

4.45 min read
Md Nasim SheikhMd Nasim Sheikh
Share:

Every frontend developer builds a weather app. It teaches you the core loop: Fetch -> State -> Render. It also forces you to handle "messy" real-world data.

Advertisement

The Setup

Get a free API key from OpenWeatherMap. Then scaffold your project:

npx create-react-app weather-app
cd weather-app

The Fetch Logic

We need to handle 3 states: loading, error, and success.

  const [weather, setWeather] = useState(null);
  const [error, setError] = useState('');
  const [city, setCity] = useState('London');

  const fetchWeather = async () => {
    setError('');
    const API_KEY = 'YOUR_KEY';
    
    try {
        const response = await fetch(
          `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}&units=metric`
        );
        
        if (!response.ok) throw new Error('City not found');
        
        const data = await response.json();
        setWeather(data);
    } catch (err) {
        setError(err.message);
        setWeather(null);
    }
  };

Component Rendering

Conditional rendering is React's superpower.

return (
  <div className="app">
    <div className="search">
        <input value={city} onChange={e => setCity(e.target.value)} />
        <button onClick={fetchWeather}>Search</button>
    </div>

    {error && <div className="error">{error}</div>}

    {weather && (
      <div className="card glass-effect">
        <h1>{weather.name}</h1>
        <h2 className="temp">{Math.round(weather.main.temp)}°C</h2>
        <p>{weather.weather[0].description}</p>
        <img 
            src={`http://openweathermap.org/img/wn/${weather.weather[0].icon}@4x.png`} 
            alt="icon" 
        />
      </div>
    )}
  </div>
);

Pro Tip: Debouncing

If you search as the user types, you will hit the API rate limit immediately. Use a debounce function (or useEffect with a timeout) to only search 500ms after the user stops typing.

Advertisement

Quiz

Quick Quiz

When fetching data in React, what is the best way to handle 'Rate Limiting' or excessive API calls from a search bar?

Conclusion

This project proves you can interact with the outside world. To extend it, try using the browser's navigator.geolocation API to automatically load the weather for the user's current location on startup.

Md Nasim Sheikh
Written by

Md Nasim Sheikh

Software Developer at softexForge

Verified Author150+ Projects
Published:

You May Also Like