Weather data is not displaying in react

Viewed 59

This is the code that is not working. I am getting a typerror called "cannot read the property of undefined ("temp")".

import React, { useEffect, useState } from "react";
import "./css/style.css";
import { BiStreetView } from "react-icons/bi";

const Tempapp = () => {
  const [city, setCity] = useState(null);
  const [search, setSearch] = useState("");

  useEffect(() => {
    const fetchApi = async () => {
      const url = `http://api.openweathermap.org/data/2.5/weatherq=${search}nits=metric&APPID=83ea3057047027c6c4521d32d69250a0`;
      const res = await fetch(url);
      const resjson = await res.json();
      // console.log(resjson);
      setCity(resjson);
    };
    fetchApi();
  }, [search]);

  return (
    <>
      <div className="box">
        <div className="inputData">
          <input
            type="search"
            className="inputField"
            value={search}
            placeholder="Enter city"
            onChange={(event) => setSearch(event.target.value)}
          />
        </div>

        {city ? (
          <div className="info">
            <h1 className="temp">{city.main.temp} °Cel</h1>
            <h1 className="weather">{city.weather[0].main}</h1>

            <h3 className="tempmin_max">
              Min : {city.main.temp_min} °Cel | Max : {city.main.temp_max} °Cel
            </h3>
          </div>
        ) : (
          <p>Not relevant</p>
        )}
      </div>
    </>
  );
};

export default Tempapp;

I am using react js and I am unable to display the weather. this is my code, in the console it is showing "TypeError: Cannot read properties of undefined (reading 'temp')" How can I solve this please help! I can display like this {setCity(resjson.main)} but unable to do like this {setCity(resjson)} Want to display the weather and temperature and minimum and maximum temperature.

API Data:

{
  "coord": {
    "lon": 73.8333,
    "lat": 15.4833
  },
  "weather": [{
    "id": 804,
    "main": "Clouds",
    "description": "overcast clouds",
    "icon": "04n"
  }],
  "base": "stations",
  "main": {
    "temp": 298.95,
    "feels_like": 299.75,
    "temp_min": 298.95,
    "temp_max": 298.95,
    "pressure": 1011,
    "humidity": 83,
    "sea_level": 1011,
    "grnd_level": 1011
  },
  "visibility": 10000,
  "wind": {
    "speed": 2.94,
    "deg": 303,
    "gust": 4.1
  },
  "clouds": {
    "all": 86
  },
  "dt": 1663596174,
  "sys": {
    "country": "IN",
    "sunrise": 1663548808,
    "sunset": 1663592632
  },
  "timezone": 19800,
  "id": 1260607,
  "name": "Panjim",
  "cod": 200
}
1 Answers

The problem is with your API fetching. When I tried running your app, I faced

TypeError: Failed to fetch 

And when I browsed through the Open Weather API documentation, I found the standard way of calling their APIs quite different than yours. Please make sure you have appropriately set up your API keys and access.

Related