ReactFix
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • React
  • React Native
  • Programming
  • Object Oriented Programming

Monday, November 7, 2022

[FIXED] How to create an array of dates in React JS

 November 07, 2022     arrays, date-fns, javascript, reactjs   

Issue

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.


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)


Answered By - Konrad Linkowski
Answer Checked By - - Willingham (ReactFix Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post Home

Featured Post

Is Learning React Difficult?

React is difficult to learn, no ifs and buts. React isn't inherently difficult to learn. It's a framework that's different from ...

Total Pageviews

Copyright © ReactFix