'React component that shows the current weather in selected city (temperature, description and weather icon)

I would like to create a react component that shows the current weather in the selected city (temperature, description, and weather icon).

I'm using OpenWeatherMap, but I don't know where I should start..

I would like it to look like this:

enter image description here

function Weather() {
    const [weather, setWeather] = React.useState();

    const fetchWeather = () => {
        fetch(
            "api.openweathermap.org/data/2.5/weather?q=Helsinki &APPID=<APP-ID>"
        )
            .then(response => response.json())
            .then(data => {
                setWeather(data.results[0].weather);
            });
    };
}

Help is needed! Thanks



Solution 1:[1]

The issue was your fetch request is missing the protocol part at the start of URL(https://).

import "./styles.css";
import React from "react";

const cityList = ["Helsinki", "Tampere", "Turku", "Oulu"];

export default function Weather() {
  const [weather, setWeather] = React.useState();
  const [city, setCity] = React.useState("Helsinki");

  const fetchWeather = (city) => {
    fetch(
      `https://api.openweathermap.org/data/2.5/weather?q=${city}&APPID=dc6e198d710d27211ed68a445d1bb01e`
    )
      .then((response) => response.json())
      .then((data) => {
        setWeather(data);
      });
  };

  React.useEffect(() => {
    fetchWeather(city);
  }, [city]);

  return (
    <div className="App">
      <div>
        <select
          onChange={(e) => {
            setCity(e.target.value);
          }}
        >
          {cityList.map((city) => (
            <option value={city}>{city}</option>
          ))}
        </select>
      </div>
      <div style={{ marginTop: "20px" }}>
        <div>Temparature : {weather?.main?.temp}</div>
        <div>Weather : {weather?.weather?.[0]?.main}</div>
      </div>
    </div>
  );
}

Edit unruffled-burnell-02vz9

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1