Skip to content
Advertisement

convert array of full date to array of month in react

i try to convert array of date to array of month in react

import React, {useEffect, useState} from 'react';
import {Line} from 'react-chartjs-2';
import moment from "moment";
const LinkChart = () => {
const link = [
"2021-01-19T18:11:33.383Z", 
"2021-03-19T18:11:40.617Z", 
"2021-04-19T18:11:47.894Z", 
"2021-05-19T18:11:53.305Z", 
"2021-06-19T18:11:55.341Z", 
"2021-07-19T18:11:59.325Z", 
"2021-07-20T07:05:29.877Z", 
"2021-07-21T09:02:08.691Z"]
    const [clicks,] = useState(link.clicks);
    const [clickDate,setClickDate] = useState([]);
    const [month,setMonth] = useState([]);


    useEffect(()=>{
            setClickDate(link.clicksDate);

            clickDate.map((l,index)=>{
                let months = []
                const convertedDateToMonths = moment(l).format('MMM');
                months.push(convertedDateToMonths) 
                return setMonth(months);
            })
    },[link,clickDate])
    
    return <>

    </>
}

export default LinkChart;

when i push convertedDateToMonths to array every time i rewrite month in output i got only 1 month when i do console.log(month) what i do wrong ?

Advertisement

Answer

You need to call the setMonth function with the updated table and not on each .map loop. So just process the links with a simple map to get the list of months and call setMonth with the result of it:

const LinkChart = () => {
  const LINKS = [
    "2021-01-19T18:11:33.383Z",
    "2021-03-19T18:11:40.617Z",
    "2021-04-19T18:11:47.894Z",
    "2021-05-19T18:11:53.305Z",
    "2021-06-19T18:11:55.341Z",
    "2021-07-19T18:11:59.325Z",
    "2021-07-20T07:05:29.877Z",
    "2021-07-21T09:02:08.691Z"
  ];
  const [months, setMonths] = useState([]);

  useEffect(() => {
    setMonths(
      LINKS.map((l) => {
        return moment(l).format("MMM");
      })
    );
  }, [LINKS]);

  // ...
};

Edit modern-waterfall-c20vi

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement