React app freezing after iterating over array in component return

248 Views Asked by At

I'm working on adding a calendar feature to my React application. I'm using this tutorial to do it. I'm trying to use Day.js instead of Moment, because Moment is in legacy mode, and Day.js was one of the recommendations. It seems that most of the functionality is the same.

Here is my basic calendar component:

const Calendar = () => {
  const [value, setValue] = useState(moment());
  const [calendar, setCalendar] = useState([]);
  const startDay = value.clone().startOf("month").startOf("week");
  const endDay = value.clone().endOf("month").endOf("week");

  useEffect(() => {
    const day = startDay.clone().subtract(1, "day");
    const a = [];
    while (day.isBefore(endDay, "day")) {
      a.push(
        Array(7)
          .fill(0)
          .map(() => day.add(1, "day").clone())
      );
    }
    setCalendar(a);
  }, [value]);

  return (
    <>
      <h1>Calendar will go here.</h1>
      <div>
        {calendar.map((week) => {
          return (
            <div>
              {week.map((day) => {
                return <div>{day.format("D").toString()}</div>;
              })}
            </div>
          );
        })}
      </div>
    </>
  );

Before I started to map through the calendar array, I only had the <h1> tag in the return, and the component rendered as I expected. I also previously printed out the values of startDay and endDay. However when I include the logic to map over the calendar array, the whole application locks up on me. I have to comment out that code and restart my server to reset everything. I'm having trouble figuring out what the problem is.

1

There are 1 best solutions below

2
On BEST ANSWER

My guess would be that day.isBefore(endDay, "day") condition is never met. I doubt day.add(1, "day") actually mutates the day variable: it most likley returns a new instance.

Just checked the docs for add:

"Returns a cloned Day.js object with a specified amount of time added."

That means you will need to use let to declare the day variable and re-assign it when adding days.