Use the API to Fetch Data

Learn how to use the API and fetch function to retrieve the data.

We’ll use an API to fetch weather data from the OpenWeather website.

Note: Because we’re using an API in this section, you need to create a personal API key from the website. You need to add the generated API key value in the api_key_weather_app value slot.

Import the hooks

To store the weather data received from the API, we must import useState to store the weather data’s current state. We’ll need to import the useEffect hook as well so that our fetch can run whenever the dependencies change. The following snippet shows how to import the required hooks:

import {useState, useEffect} from the "react"

Use the hooks

We’ll assign the imported hooks to the variables and give them initial values. Using the state updating function setWeatherData the data obtained from the API is in the weatherData variable. When working with APIs, we may encounter some errors. To deal with these, we need to change the error state to the value true by using the setError function. Initially, the value of the error state is false.

const [weatherData, setWeatherData] = useState({});
const [error, setError] = useState(false);

Fetch data using the API

We’ll now use the same API that we discussed in the Learn About APIs lesson. Here it is:

//  Weather API
const URL = `https://api.openweathermap.org/data/2.5/weather?q=${cityName}&appid={{api_key_weather_app}}`;

Note: Remember to use your personal API key value instead of {{api_key_weather_app}}.

We use the JavaScript fetch() method to retrieve the data from the website. Then, we define the fetchData function and store the data received from the API in the weatherData. If we get the 404 error while fetching the data, we use the setError to make the error variable true. The following snippet shows how to use fetch to fetch data with the API.

//  Fetching weather data
async function fetchData(URL) {
  const response = await fetch(URL);
  const data = await response.json();
  if (data.cod === "404") {
    setError(true);
  } else {
    setWeatherData(data);
  }
}

Note: Read more about the fetch method from the Educative Answer post on fetch.

We’ll now use useEffect to call the fetchData function every time the dependency changes. We assign the URL as the dependency.

//  To fetch weather data
useEffect(() => {
  fetchData(URL);
}, [URL]);

Pass data in the ShowWeather component

To pass data in the ShowWeather component, we have to import it and pass it as shown in the following snippet:

import ShowWeather from "./ShowWeather"

return (
   ...
   <ShowWeather data={weatherData}/>
)

Because we’ve yet to create the layout for our ShowWeather component, we won’t be able to see the actual output in the application. For now, we can use console.log() to view the data temporarily. Here’s how to do it:

console.log(weatherData)

Combining all the code snippets above produces the following code:

Get hands-on with 1400+ tech skills courses.