DEV Community

Utsav Mavani
Utsav Mavani

Posted on

ReactJS to fetch weather data from a weather API

ReactJS to fetch weather data from a weather API based on the user's location. In this example, we'll use the OpenWeatherMap API to get weather information. You'll need to sign up for an API key from OpenWeatherMap to use their service.

Here's a simple implementation:

  1. Create a new React app (if you don't have one already) using create-react-app or your preferred method.
  2. Install the necessary dependencies: You'll need to install the axios library to make API requests. You can install it using: npm install axios
  3. Create a Weather component:

Create a new component, let's call it Weather.js. This component will handle fetching weather data and displaying it.

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const Weather = () => {
  const [weatherData, setWeatherData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    // Function to fetch weather data
    const fetchWeatherData = async () => {
      try {
        // Get user's location using the browser's geolocation API
        navigator.geolocation.getCurrentPosition(async (position) => {
          const { latitude, longitude } = position.coords;

          // Replace 'YOUR_API_KEY' with your actual OpenWeatherMap API key
          const apiKey = 'YOUR_API_KEY';
          const apiUrl = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${apiKey}&units=metric`;

          const response = await axios.get(apiUrl);
          setWeatherData(response.data);
          setLoading(false);
        });
      } catch (error) {
        setError(error);
        setLoading(false);
      }
    };

    fetchWeatherData();
  }, []);

  if (loading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>Error: {error.message}</div>;
  }

  if (!weatherData) {
    return <div>No weather data available.</div>;
  }

  return (
    <div>
      <h1>Weather Information</h1>
      <p>Location: {weatherData.name}, {weatherData.sys.country}</p>
      <p>Temperature: {weatherData.main.temp}°C</p>
      <p>Weather: {weatherData.weather[0].description}</p>
    </div>
  );
};

export default Weather;
Enter fullscreen mode Exit fullscreen mode
  1. Use the Weather component:
import React from 'react';
import Weather from './Weather';

function App() {
  return (
    <div className="App">
      <Weather />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Remember to replace 'YOUR_API_KEY' with your actual OpenWeatherMap API key in the Weather.js file.

This example demonstrates how to fetch weather data using the user's location. However, keep in mind that using the browser's geolocation API might prompt the user for permission to access their location.

Top comments (1)

Collapse
 
darkmavis1980 profile image
Alessio Michelini

While I understand this is a simple example of how to fetch weather data from an API, has a rather big flaw: you are placing an API KEY in a front facing code, that can be easily found even by scrapers, and while it serves the example, it's a general bad practice.
What you should do instead is create a simple backend, that you can call from the client, and you keep the API KEY in the backend, so it's not visible by anybody.