Home > Software engineering >  Array created using dayjs outputs undefined elements
Array created using dayjs outputs undefined elements

Time:12-09

I am trying to make a react calendar using dayJs library, I create a 2d array for month using the following code :

import dayjs from "dayjs";

export const getMonth = (month = dayjs().month()) => {
    const year = dayjs().year();
    const firstDayOfMonth = dayjs(new Date(year, month, 1)).day();
    let currentMonthCount = 0 - firstDayOfMonth;
    const daysMatrix = new Array(5).fill([]).map(() => {
        return new Array(7).fill(null).map(() => {
            currentMonthCount  
            return dayjs(new Date(year, month, currentMonthCount))
        })
    });
    return daysMatrix;
};

now when I import the function in my app.js file and pass it onto another component month.js which displays the array using the following code :

import React, { Fragment } from 'react';
import Day from '../components/Day';

const Month = ({ month }) => {
  if(month) {
    month.map((e) => console.log(e));
  }
  return (
    <div className='flex-1 grid grid-cols-7 grid-rows-5'>
      {month.map((row, i) => (
        <Fragment key={i}>
          {row.map((day, j) => (
            <Day day={day} key={j} />
          ))}
        </Fragment>
      ))}
    </div>
  )
};
export default Month;

here, the console log outputs the month array as it should but I get an error in the return section stating unable to read properties of undefined reading map, could someone please explain why am I getting this error although the map worked fine for the console.log statement?

my app.js file :

import React, { useState } from 'react';
import './App.css';
import { getMonth } from './util';
import { Fragment } from 'react';
import CalendarHeader from './components/CalendarHeader';
import Sidebar from './components/Month';
import Month from './components/Month';

function App() {
  const [currentMonth, setCurrentMonth] = useState(getMonth());
  return (
    <Fragment>
      <div className='h-screen flex flex-col' >
        <CalendarHeader />
        <div className="flex flex-1">
          <Sidebar />
          <Month month={currentMonth} />
        </div>
      </div>
    </Fragment>    
  );
}

export default App;

CodePudding user response:

unable to read properties of undefined reading map this kind of error can occur when you are trying to loop over or using the map method over an undefined value. To resolve this you can use Optional chaining (?.).

In your case, you need to use this in Month component as done below:

{month?.map((row, i) => (
        <Fragment key={i}>
          {row?.map((day, j) => (
            <Day day={day} key={j} />
          ))}
        </Fragment>
      ))}

Let me know if this works for you.

  • Related