Reputation: 43
I'm using chart js, I tried to edit the dates created from my MongoDB to check if it will represent according to the given month. As shown in the image, the line is not arranged according to its given month index.
How can I arrange the line chart according to the month created? Is the logic I put in the useEffect wrong?
const Home = () => {
const [userStats, setUserStats] = useState([])
const MONTHS = useMemo(
() => [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Agu',
'Sep',
'Oct',
'Nov',
'Dec',
],
[]
)
useEffect(() => {
const getStats = async () => {
try {
const res = await userRequest.get('/user/stats')
res.data.map((item) =>
setUserStats((prev) => [
...prev,
{ name: MONTHS[item._id - 1], 'Active User': item.total },
])
)
} catch {}
}
getStats()
}, [MONTHS])
console.log(userStats)
return (
<div className="home">
<Featured />
<Chart
data={userStats}
title="user Analaytics"
grid
dataKey="Active User"
/>
<div className="homeWidgets">
<Widget />
<WidgetLg />
</div>
</div>
)
}
export default Home
and each time I refresh the page, the arrangement of it gets rendered random.
Upvotes: 1
Views: 423
Reputation: 43
Okay I found it, I used sort method, and grabbed the id of it
const list = res.data.sort((a, b) => {
return a._id - b._id
})
list.map((item) =>
setUserStats((prev) => [
...prev,
{ name: MONTHS[item._id - 1], 'Active User': item.total },
])
Upvotes: 1