Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create an array of dates in React JS

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading