Search code examples
javascriptreactjsajaxreduxpreloader

How to solve error Cannot read property '1' of undefined?


So guys, I'm making preloader for my React App but I have an error.


I'm using thunk to change status of preloader (true/false) and in component it looks like:

{isLoading === true ? <Preloader />  :
                <div className="daily-weather-container">
                    <div className="daily-title">Daily Weather</div>
                    <div className="row scrolling-wrapper ">
                        <div className="col-lg-2 box-daily-weather">
                            {getWeatherStatistic(1)}
                        </div>
                    </div>
                </div>
            }
        </div>
    )
}
const getWeatherStatistic = (value) => {
        return (
            <div>
                <div className="date-box">5 June, Friday</div>
                <div className="temp-day">{Math.ceil(dailyData.daily[value].temp.day)}°C</div>
                <div className="feels-like">Feels like: {Math.ceil(dailyData.daily[value].feels_like.day)}°C</div>
                <div className="daily-weather-condition">Conditions: {dailyData.daily[value].weather.map(e => e.main)}</div>
            </div>
        )
    }

And It works, but the problem is here {getWeatherStatistic(1)}. 1 - object index which I get from ajax request. So this error happened because, when the user open my App the state is empty, so it can't gets index object (obviously it not exists before making request).


So how to solve this problem?


Solution

  • Assure yourself dailyData.daily is a proper array and it won't crash

    const getWeatherStatistic = (value) => {
        if(dailyData && Array.isArray(dailyData.daily){
            return (
                <div>
                    <div className="date-box">5 June, Friday</div>
                    <div className="temp-day">{Math.ceil(dailyData.daily[value].temp.day)}°C</div>
                    <div className="feels-like">Feels like: {Math.ceil(dailyData.daily[value].feels_like.day)}°C</div>
                    <div className="daily-weather-condition">Conditions: {dailyData.daily[value].weather.map(e => e.main)}</div>
                </div>
            )
        }
        else{
            return (
                <div>Loading...</div>
            )
        }
    }