i try to convert array of date to array of month in react
JavaScript
x
36
36
1
import React, {useEffect, useState} from 'react';
2
import {Line} from 'react-chartjs-2';
3
import moment from "moment";
4
const LinkChart = () => {
5
const link = [
6
"2021-01-19T18:11:33.383Z",
7
"2021-03-19T18:11:40.617Z",
8
"2021-04-19T18:11:47.894Z",
9
"2021-05-19T18:11:53.305Z",
10
"2021-06-19T18:11:55.341Z",
11
"2021-07-19T18:11:59.325Z",
12
"2021-07-20T07:05:29.877Z",
13
"2021-07-21T09:02:08.691Z"]
14
const [clicks,] = useState(link.clicks);
15
const [clickDate,setClickDate] = useState([]);
16
const [month,setMonth] = useState([]);
17
18
19
useEffect(()=>{
20
setClickDate(link.clicksDate);
21
22
clickDate.map((l,index)=>{
23
let months = []
24
const convertedDateToMonths = moment(l).format('MMM');
25
months.push(convertedDateToMonths)
26
return setMonth(months);
27
})
28
},[link,clickDate])
29
30
return <>
31
32
</>
33
}
34
35
export default LinkChart;
36
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:
JavaScript
1
24
24
1
const LinkChart = () => {
2
const LINKS = [
3
"2021-01-19T18:11:33.383Z",
4
"2021-03-19T18:11:40.617Z",
5
"2021-04-19T18:11:47.894Z",
6
"2021-05-19T18:11:53.305Z",
7
"2021-06-19T18:11:55.341Z",
8
"2021-07-19T18:11:59.325Z",
9
"2021-07-20T07:05:29.877Z",
10
"2021-07-21T09:02:08.691Z"
11
];
12
const [months, setMonths] = useState([]);
13
14
useEffect(() => {
15
setMonths(
16
LINKS.map((l) => {
17
return moment(l).format("MMM");
18
})
19
);
20
}, [LINKS]);
21
22
// ...
23
};
24