Home > Net >  How to create an array of dates in React JS
How to create an array of dates in React JS

Time:11-08

I am trying to create an array of days, starting from the current day, up to some range that I could modify (for example, 60 days), but I am not succeeding.

Here is my code:

import { useEffect, useState } from 'react';
import { add } from 'date-fns'

export const Datepicker = () => {

    const [daysArray, setDaysArray] = useState([ new Date() ]);

    const daysRange = 60;

    useEffect(() => {
        for (let i = 0; i < daysRange; i  ) {
            setDaysArray([ ...daysArray, add(new Date(), { days: i }) ]);
            
        }
        
    }, []);

    console.log(daysArray)

I'm waiting for an output like this:

0: Mon Nov 07 2022 18:57:14 GMT-0300
1: Tue Nov 08 2022 18:57:14 GMT-0300
2: Wed Nov 09 2022 18:57:14 GMT-0300
3: Thu Nov 10 2022 18:57:14 GMT-0300
Etc... up to the range that I have entered

But my output looks like this:

0: Mon Nov 07 2022 18:57:14 GMT-0300
1: Thu Jan 05 2023 18:57:14 GMT-0300

What am I doing wrong?

I suppose there are better ways to do this than using a for loop, but I really don't know what the best practices are in this case.

CodePudding user response:

daysArray has the same value in every iteration

Easy fix:

for (let i = 0; i < daysRange; i  ) {
  setDaysArray(daysArray => [ ...daysArray, add(new Date(), { days: i }) ]);            
}

Better fix:

const array = []
for (let i = 0; i < daysRange; i  ) {
  array.push(add(new Date(), { days: i }));            
}
setDaysArray(array)
  • Related