Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

javascript - unable to fetch data. Unhandled Rejection (TypeError): Cannot read property '0' of undefined

I am using async to fetching data . Its get loaded successfully but when i type new value in input field or refresh the page .I get the following error that the Cannot read property '0' of undefined

Unhandled Rejection (TypeError): Cannot read property '0' of undefined

import React, { useEffect, useState } from "react";
import { API } from "../api";

const Weather = () => {
  const [city, setCity] = useState("");
  const [search, setSearch] = useState("Mumbai");
  const [wind, setWind] = useState("");
  const [weather, setWeather] = useState([]);

  const fetchApi = async () => {
    const url = `https://api.openweathermap.org/data/2.5/weather?q=${search}&units=metric&appid={key}`;
    const response = await fetch(url);
    const res = await response.json();
    setCity(res.main);
    setWeather(res.weather[0].main);
  };

  useEffect(() => {
    fetchApi();
  }, [search]);

  return (
    <div className="container col-md-6 ">
      <div className="card rounded">
        <div className="card-body">
          <input
            type="search"
            className=" searchbox offset-md-3 col-md-6"
            value={search}
            onChange={(e) => {
              setSearch(e.target.value);
            }}
          />
          {!city ? (
            <>
              <p className="text-center mt-3">No city found</p>
            </>
          ) : (
            <div className="info text-center mt-3">
              <h1 className="mr-2">
                <i className="fas fa-street-view "></i>
              </h1>
              <h2>{search}</h2>
              <h6>{Date()}</h6>

              <span className="row"></span>
              <h3>{city.temp}°C</h3>

              <h5 className="min_max text-danger">
                Humidity:{city.humidity} | Min :{city.temp_min} | Max:{" "}
                {city.temp_max}
              </h5>
              <h1>{weather}</h1>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default Weather;
question from:https://stackoverflow.com/questions/65923521/unable-to-fetch-data-unhandled-rejection-typeerror-cannot-read-property-0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Update

I try with try and catch block . If the error may occur it will be log to the console and it works fine

const fetchApi = async () => {
try {
  const url = `https://api.openweathermap.org/data/2.5/weather?q=${search}&units=metric&appid={key}`;
  const response = await fetch(url);
  const res = await response.json();
  setCity(res.main);
  setWeather(res.weather[0].main);
  setWind(res.wind);
} catch (err) {
  console.log(err);
}

};


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...