I have a functional component named Calendar wherein each month is a Button. The API I have designed sends the data in the following format:
[
{
"month": 1,
"count": 5
},
{
"month": 3,
"count": 2
},
{
"month": 10,
"count": 4
},
{
"month": 11,
"count": 3
}
]
Now I have the following states:
const [jan, setJan] = useState(0);
const [feb, setFeb] = useState(0);
const [mar, setMar] = useState(0);
const [apr, setApr] = useState(0);
const [may, setMay] = useState(0);
const [june, setJune] = useState(0);
const [july, setJuly] = useState(0);
const [aug, setAug] = useState(0);
const [sept, setSept] = useState(0);
const [oct, setOct] = useState(0);
const [nov, setNov] = useState(0);
const [dec, setDec] = useState(0);
const [month, setMonth] = useState([]);
Using the useEffect, I have set the month and stored the data in the month state, but when I use console.log(month) it shows an empty array,
useEffect(() => {
axios.get("http://localhost:8081/api/CalendarNotification/1234")
.then(res => {
setMonth(res.data)
})
.catch(err => { console.log(err) })
}, []);
And now I have used the below code, to set each month's state according to the "month" in the data received from the api.
{
(month.map(mon => {
if (mon["month"] === 1)
setJan(mon["count"]);
else if (mon["month"] === 2)
setFeb(mon["count"]);
else if (mon["month"] === 3)
setMar(mon["count"]);
else if (mon["month"] === 4)
setApr(mon["count"]);
else if (mon["month"] === 5)
setMay(mon["count"]);
else if (mon["month"] === 6)
setJune(mon["count"]);
else if (mon["month"] === 7)
setJuly(mon["count"]);
else if (mon["month"] === 8)
setAug(mon["count"]);
else if (mon["month"] === 9)
setSept(mon["count"]);
else if (mon["month"] === 10)
setOct(mon["count"]);
else if (mon["month"] === 11)
setNov(mon["count"]);
else if (mon["month"] === 12)
setDec(mon["count"]);
}
))}
Also, where do I write the code, in the useEffect or the return method, please let me know!
But nothing works, can someone please help with the same. Thanks a ton in advance! :)
usually you have to try to update your individual months inside an useEffect. Also you need to use forEach function to do this kind of operation. map function is intended to return something . Something like this should work
useEffect(() => {
month.forEach(mon => {
// UPDATE YOUR INDIVIDUAL MONTHS HERE
})
},[ month ])