Sanira Liyanage
Sanira Liyanage

Reputation: 1237

Concat Dates Array is changing the Date in the last index of the array

I have implemented a function to get a Date object and a count as parameters and return an array of Date objects from the passed 'date' to 'count' times. However, the issue comes with the next bit of code I was writing, initially, I have generated an array of dates using that function, and again on click of a button, I'm trying to pass the last date of the initial array to that function and concatenate the newly returned array to the initial array. the issue is whenever I pass the last date of the initial array to the function, the date in the last index of the initial array is changed to the new array's date of the first index. I can't wrap my head around for a solution for this still. here's what I have.

const getDatesArray = (fromDate: Date, howManyDays: number) => {
  const tempDate = fromDate;
  const datesArray: Date[] = [];
  for (let i = 0; i < howManyDays; i++) {
    if (i === 0) {
      datesArray.push(new Date(tempDate.setDate(tempDate.getDate() + 0)));
    } else {
      datesArray.push(new Date(tempDate.setDate(tempDate.getDate() + 1)));
    }
  }
  return datesArray;
}

const handleNextClick = () => {
    /* adding a week to the date stripe dats array */
    const lastDate = datesData[datesData.length - 1];
    const nextDate = new Date(lastDate.setDate(lastDate.getDate() + 1));
    setDatesData(datesData.concat(getDatesArray(new Date(nextDate), datesToDisplay)));
}

As I observe this const nextDate = new Date(lastDate.setDate(lastDate.getDate() + 1)); line causes the problem. Any ideas how to accomplish this?

Upvotes: 0

Views: 32

Answers (1)

You're right about the problem line. const nextDate = new Date(lastDate.setDate(lastDate.getDate() + 1)); means "add 1 to lastDate, and then make nextDate with the same value as the newly-updated lastDate." You want this instead:

const nextDate = new Date(lastDate.getTime());
nextDate.setDate(nextDate.getDate() + 1);

That means "make nextDate with the same value as lastDate, and then add 1 to nextDate."

Upvotes: 1

Related Questions