почему не могу получить элемент из массива?

Рейтинг: 1Ответов: 1Опубликовано: 21.01.2023

хочу сделать запрос на сервер и получить объект, с этого объекта хочу получить поле weather, это массив объектов, но мне нужен только первый, и с него хочу получить поле main. Если не обновлять страницу то все работает. Если обновить то вылезает ошибка

CurrentWeather.jsx:40 Uncaught TypeError: Cannot read properties of undefined (reading '0')

Подскажите, пожалуйста, что делаю не так.

получаю нужный объект

const [currentWeather, setCurrentWeather] = useState({})
const [getWeather, isWeatherLoading, weatherError] = useFetching(async () => {
    const resopose = await axios.get(url)
    setCurrentWeather(resopose.data)
})
useEffect(() => {
        getCurrentCity()
        getWeather()
    }, [city, urlForCurrentCity])

далее пытаюсь его вывести

isWeatherLoading
               ? 
               <Loader/>
               :
               <div>{currentWeather?.weather[0]?.main}</div>

хук useFetching

import {useState} from "react";

export const useFetching = (callback) => {
    const [isLoading, setIsLoading] = useState(true)
    const [error, setError] = useState('')

    const fetching = async () => {
        try {
            setIsLoading(true)
            await callback()
        } catch (e) {
            setError(e.message)
        } finally {
            setIsLoading(false)
        }
    }
    return [fetching, isLoading, error]
}

объект, который прилетает с сервера

{
    "coord": {
        "lon": -0.1257,
        "lat": 51.5085
    },
    "weather": [
        {
            "id": 800,
            "main": "Clear",
            "description": "clear sky",
            "icon": "01n"
        }
    ],
    "base": "stations",
    "main": {
        "temp": 0.18,
        "feels_like": 0.18,
        "temp_min": -2.43,
        "temp_max": 1.98,
        "pressure": 1035,
        "humidity": 88
    },
    "visibility": 10000,
    "wind": {
        "speed": 0,
        "deg": 0
    },
    "clouds": {
        "all": 5
    },
    "dt": 1674330102,
    "sys": {
        "type": 2,
        "id": 2006068,
        "country": "GB",
        "sunrise": 1674287636,
        "sunset": 1674318546
    },
    "timezone": 0,
    "id": 2643743,
    "name": "London",
    "cod": 200
}

Ответы

▲ 1Принят

В момент первоначального рендеринга, ваш currentWeather является пустым объектом. У пустого объекта нет ключа weather, что и приводит к ошибке Uncaught TypeError: Cannot read properties of undefined (reading '0').

Как исправить?

Вариант один:

Сделать начальное состояние, содержащее ключ weather

const [currentWeather, setCurrentWeather] = useState({ weather: []})

Вариант два:

В рендеринге проверить, что массив существует

isWeatherLoading
    ? 
    <Loader/>
    :
    {currentWeather?.weather?.lenght > 0 && 
        <div>{currentWeather.weather[0].main}</div>
    }