Home > front end >  Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'slice')
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'slice')

Time:09-23

I am getting the error Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'slice')

const formatForecastWeather = (data) => {
    let { timezone, daily, hourly } = data;
    daily = daily.slice(1, 6).map(d => { //i am geeting error on this line 
        return {
            title: formatToLocalTime(d.dt, timezone, 'ccc'),
            temp: d.temp.day,
            icon: d.weather[0].icon
        }
    });


    hourly = hourly.slixe(1, 6).map(d => {
        return {
            title: formatToLocalTime(d.dt, timezone, 'hh:mm a'),
            temp: d.temp.day,
            icon: d.weather[0].icon
        }
    });

    return { timezone, daily, hourly };

};

CodePudding user response:

You can put an Optional Chaining operator ? In order to avoid “read properties of undefined error”.

const formatForecastWeather = (data) => {
    let { timezone, daily, hourly } = data;
    daily = daily?.slice(1, 6).map(d => { //i am geeting error on this line 
        return {
            title: formatToLocalTime(d.dt, timezone, 'ccc'),
            temp: d.temp.day,
            icon: d.weather[0].icon
        }
    });
  • Related