Home > Software design >  Cannot read properties of undefined (reading 'DateTime') even I check there is a data in R
Cannot read properties of undefined (reading 'DateTime') even I check there is a data in R

Time:12-22

I'm just getting learning React a few weeks ago. So, If I ask a pretty general question, I am sorry. But, It would be really appreciated if you help me out!

  • Issue : Cannot read properties of undefined (reading 'DateTime')

  • What I try to solve it : Firstly, I tried to solve it generally. I mean I add the condition to progress my code and re-render. Also, I check the data exist or not.

  • Code

  const changeWeekendDateColor = () => {
    let eventArray = [];
    let weekendArray = [];
    if (weekendData && weekendData.event && weekendData.schedule) {
      let status = false;
      const dataEventLength = weekendData.event.length;
      const dataWeekendLength = weekendData.schedule.length;

      for (let i = 0; i <= dataEventLength; i  ) {
        eventArray.push(weekendData.event[i].DateTime.split("T")[0]);
      }

      for (let i = 0; i <= dataWeekendLength; i  ) {
        weekendArray.push(weekendData.schedule[i].split(" ")[0]);
      }
    }

    for (let i = 0; i <= eventArray.length; i  ) {
      if (weekendArray.includes(eventArray[i])) return (status = false);
    }

    return status;
  };
  console.log(changeWeekendDateColor(weekendData));

WeekendData is this one

enter image description here

  • What I expect : I add if statement
if (weekendData && weekendData.event && weekendData.schedule)

So, I think this should be work because if there is no data, it shouldn't do the next line. I am not sure why my code couldn't approach the weekendData.event.DateTime...

enter image description here

CodePudding user response:

for loop can't read undefiened property. dataWeekendLength has 7 length but weekendData.event only have 1 length from the array.

See WeekendData.schedule.length

...
schedule: Array(7)

And this is for loop in the code,

      for (let i = 0; i <= dataEventLength; i  ) {
        eventArray.push(weekendData.event[i].DateTime.split("T")[0]);
      }

The for loops 7 times for the dataEventLength,

It's weekendData.event,

...
event: Array(1)

If the for loop goes on i = 1 then it will be weekendData.event[1].

But there is no weekendData.event[1] but only weekendData.event[0].

The code would work but the array only has one.

  • Related