JiwanJeon94
JiwanJeon94

Reputation: 415

Even though I check there exsist a data, the error message shows "Cannot read properties of undefined" in React

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,

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')"

{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

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>

Upvotes: 1

Views: 51

Answers (1)

Amila Senadheera
Amila Senadheera

Reputation: 13245

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>

Upvotes: 1

Related Questions