简体   繁体   中英

TypeError: Cannot read properties of undefined (reading 'country') Whenever I search for a city

I am using Open weather map and Reactjs.

The problem is found in my WeatherContainer component.

I want my search bar to work. But whenever I search for a city I get this error:

控制台错误

I have tried changing the API key but it does nothing.

The code error line is pointing at:

源错误

I get my data like this:

WeatherContainer.tsx:

const [weather, setWeather] = useState({
    city: "",
    country: "",
    temperature: 0,
    description: "",
    icon: "",
    humidity: "",
    feels: "",
    visibility: "",
    pressure: "",
    longitude: "",
    latitude: "",
    windSpeed: "",
  });

  useEffect(() => {
    if (fetchedData)
      setWeather({
        city: fetchedData.name,
        country: fetchedData.sys.country,
        temperature: Math.floor(fetchedData.main.temp - 273),
        description: fetchedData.weather[0].description,
        icon: `http://openweathermap.org/img/wn/${fetchedData.weather[0].icon}.png`,
        humidity: fetchedData.main.humidity + "%",
        feels: Math.floor(fetchedData.main.feels_like - 273) + "°C",
        visibility: fetchedData.visibility + "m",
        pressure: fetchedData.main.pressure + "hPa",
        longitude: fetchedData.coord.lon,
        latitude: fetchedData.coord.lat,
        windSpeed: fetchedData.wind.speed + "m/s",
      });
  }, [fetchedData]);

Edit:

This is how I defined fetchedData

export const WeatherContainer = ({
  fetchedData,
  error,
}: {
  fetchedData: any;
  error: string;
}) => {
  const [weather, setWeather] = useState({
    city: "",
    country: "",
    temperature: 0,
    description: "",
    icon: "",
    humidity: "",
    feels: "",
    visibility: "",
    pressure: "",
    longitude: "",
    latitude: "",
    windSpeed: "",
  });

  useEffect(() => {
    if (fetchedData)
      setWeather({
        city: fetchedData.name,
        country: fetchedData.sys.country,
        temperature: Math.floor(fetchedData.main.temp - 273),
        description: fetchedData.weather[0].description,
        icon: `http://openweathermap.org/img/wn/${fetchedData.weather[0].icon}.png`,
        humidity: fetchedData.main.humidity + "%",
        feels: Math.floor(fetchedData.main.feels_like - 273) + "°C",
        visibility: fetchedData.visibility + "m",
        pressure: fetchedData.main.pressure + "hPa",
        longitude: fetchedData.coord.lon,
        latitude: fetchedData.coord.lat,
        windSpeed: fetchedData.wind.speed + "m/s",
      });
  }, [fetchedData]);

I used this API https://openweathermap.org/current . I just tried to follow this documentation so I copied the link to API they have.


Edit # 2

This is the file Where I make the connection:

const API_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

export const getWeatherCoordinates = async (
  LAT: number,
  LON: number
): Promise<any> => {
  const API_URL = `https://api.openweathermap.org/data/2.5/weather?lat=${LAT}&lon=${LON}&appid=${API_KEY}`;

  const respCoordinates = await fetch(API_URL);
  const dataCoordinates = await respCoordinates.json();
  return dataCoordinates;
};
export const getWeatherSearch = async (CITY: string): Promise<any> => {
  const API_CITY = `https://api.openweathermap.org/data/2.5/weather?q=${CITY}&appid={API_KEY}`;
  const respCity = await fetch(API_CITY);
  const dataCity = await respCity.json();
  return dataCity;
};

The API response is:

{"cod":401, "message": "Invalid API key. Please see http://openweathermap.org/faq#error401 for more info."}

api链接

Based on the error image you posted and the source code, it seems like missed a $ sign in front of {API_KEY} in getWeatherSearch :

export const getWeatherSearch = async (CITY: string): Promise<any> => {
  const API_CITY = `https://api.openweathermap.org/data/2.5/weather?q=${CITY}&appid=${API_KEY}`; // <- HERE 
  const respCity = await fetch(API_CITY);
  const dataCity = await respCity.json();
  return dataCity;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM