Home > Software design >  Even though I check there exsist a data, the error message shows "Cannot read properties of und
Even though I check there exsist a data, the error message shows "Cannot read properties of und

Time:12-20

I am just getting started learning React one month ago. I am sorry if I asked a pretty easy question in advance.

Here is an issue,

  • what's the problem? : I got data from back-end that is called "setWeekendEventData". When I console WeekendEventData, I can check I received the data that I want. WeekendEventData

Here, I only want DayName. In this case, there are two DayNames. So, I tried to use the 'map' method because sometimes the DayName could be one or two or more than three. First, I tried to like this

{weekendEventData.map((obj, index) => {
                return <RedText>{obj[index].DayName}</RedText>;
              })}

However, I got this error message "Cannot read properties of undefined (reading 'DayName')"

  • What I tried to do
{weekendEventData && weekendEventData.map((obj, index) => {
                return <RedText>{obj[index].DayName}</RedText>;
              })}

and

{[] && weekendEventData.map((obj, index) => {
                return <RedText>{obj[index].DayName}</RedText>;
              })}

I add the && condition to make it always true but there is the same error message. Usually, I solved this kind of error message by using && condition but it didn't work this time.

  1. Using "Condition ? : " but it also didn't work
  • What I expected: It should be return DayName which is '개천절' and '한글날'

I would really appreciate your comments or solution!

edit 1:

const holiday = data => {
    let array = [];
    for (let i = 0; i <= 6; i  ) {
      if (data) {
        if (array.includes(data[i])) i  ;
        else array.push(data[i]);
      }
      console.log("데이터 값", data[i]);
      console.log("휴무일 배열", array);
    }

and in the functional component

<RedText>{holiday(weekendData)}</RedText>

CodePudding user response:

You use index wrongly here

obj[index].DayName

It should be corrected safely as below

obj.DayName || ""

Following will work with duplicates removed

<RedText>
    {weekendEventData &&
        weekendEventData
            .reduce((prevValue, currValue) => {
                prevValue.indexOf(currValue.DayName) < 0 &&
                    prevValue.push(currValue.DayName);
                return prevValue;
            }, [])
            .join(", ")}
</RedText>
  • Related