Getting Weather Data using an API in React

Sat Mar 25 2023

In this tutorial, we will learn how to build a weather app in React using an API to get weather data. The weather data will be fetched from the WeatherAPI.com API, which provides a free plan for developers.

To follow along with this tutorial, you should have a basic understanding of React and JavaScript.

First, create a new React app by running the following command in your terminal:

npx create-react-app weather-app

Before we can use the weatherapi.com API, we need to create an account and get an API key. Follow these steps to get your API key:

  1. Go to the weatherapi

  2. Click on "Signup" in the top-right corner of the page.

  3. Fill in the required details to create an account.

  4. Once you're signed in, go to the dashboard

  5. Copy your API key, which you'll need.

Next, open the project in code editor. Replace the content of App.js file with the following

import { useState } from "react";
import Data from "../components/Data";
import "./App.css";

function App() {
  const [data, setData] = useState();
  const [city, setCity] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError(null);

    const API_KEY = 'ae4cde8428054b1e8dd161909232503';
	
    const res = await fetch(
      `http://api.weatherapi.com/v1/current.json?key=${API_KEY}&q=${city}&aqi=no`
    );
    const result = await res.json();
    if (res.ok) {
      setData(result);
      setLoading(false);
      setCity("");
      return;
    }
    setError(result.error.message);
    setLoading(false);
  };
  if (loading) {
    return <h3>Loading...</h3>;
  }
  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          placeholder="City name"
          value={city}
          onChange={(e) => setCity(e.target.value)}
        />
        <button>Get Data</button>
      </form>
      {error && <p>{error}</p>}
      {!error && data && <Data data={data} />}
    </div>
  );
}

export default App;

We initialized four state variables:

  • data - holds the weather data fetched from the API.

  • city - holds the city entered by the user.

  • loading - indicates if the weather data is being fetched or not.

  • error - holds any errors that occur during the fetching process.

The handleSubmit function is triggered when the user submits the form. It makes an HTTP GET request to the WeatherAPI.com API with the city entered by the user. If the request is successful, the weather data is stored in the data state variable. You can log the data to see which fields are available to you. If the request fails, the error message is stored in the error state variable.

Now create a directory components and inside it create a file Data.js and paste the following code

import React from "react";

const Data = ({ data }) => {
  return (
    <div>
      <div>
        Location: {data.location.name} - {data.location.country}
      </div>
      <p style={{ display: "flex", alignItems: "center" }}>
        Condition: {data.current.condition.text} -{" "}
        <img src={data.current.condition.icon} alt="" />
      </p>
      <p>Time: {data.location.localtime}</p>

      <p>Temperature: {data.current.temp_c} C</p>

      <p>Feels like: {data.current.feelslike_c} C</p>
    </div>
  );
};

export default Data;

Here we are displaying a few fields from the response we get. And that's it! We have successfully created a weather app that fetches weather data using an API and displays it to the user.

Share

Privacy Policy
icon
icon
icon
icon

Developed By Farhan Farooq