2

I have a function that returns an array of objects like this:

getMonthDaysGrid() {
    const totalLastMonthDays = this.getFirstDayOfMonth().dayNumber;
    const totalDays = this.month.numberOfDays + totalLastMonthDays;
    const monthList = Array.from({ length: totalDays });

    for (let i = totalLastMonthDays; i < totalDays; i++) {
      monthList[i] = {
        date: i - totalLastMonthDays + 1,
        month: this.month.name,
        year: this.month.year,
      };
    }

    return monthList;
  }

when I try to make a v-for div like this:

<div v-for="(day, idx) in cal.getMonthDaysGrid()" :key="idx">
        <p>
          {{ day.date }}
        </p>
      </div>

this throw me this error:

enter image description here

I can't figure how to fix it... if it loops the array, how is that I can't access the object properties?

3
  • 1
    By the looks of it, your array has an element 0, which probably never gets filled. Commented Jun 26, 2022 at 21:48
  • @GuidoFaecke I agree. Commented Jun 26, 2022 at 21:52
  • If i put this <div v-for="(day, idx) in cal.getMonthDaysGrid()" :key="idx"> <p> {{ day }} </p> </div> it shows the object... but when i point a property it shows error Commented Jun 26, 2022 at 21:54

1 Answer 1

3

It seems like Vue is trying to access the property before it is even seem so you would have to check if it exist first or just give the day array a default value

try changing your code to

<div v-for="(day, idx) in cal.getMonthDaysGrid()" :key="idx">
        <p>
          {{ day && day.date }}
        </p>
      </div>

or to

<div v-for="(day, idx) in cal.getMonthDaysGrid()" :key="idx">
        <p>
          {{ day?.date }}
        </p>
      </div>
Sign up to request clarification or add additional context in comments.

1 Comment

I go thru this all the in react when fetching api calls, so I was very familiar with this situation. No problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.