I am trying to implement the 'react big calendar' into my application. The way I am filling it up with events does work, but it only shows these events when the calendar rerenders (by pressing a button, clicking an event etc.). My guess is that it has something to do with the useState only being filled up after the calendar has rendered, but I really have no idea on how to fix this.
I'm getting my data through an Axios request to a private API from the getCalendarData() function.
I would really appreciate it if someone could help me with this, I cannot find something like this anywhere online.
const CalendarList = (props) => {
const[calendarEvents, setEvents]= useState([])
const authAxios = axios.create({
headers: {
Authorization: 'Bearer ' + props.accesToken
}
})
useEffect(() => {
const calendarData = getCalendarData();
setEvents(calendarData);
}, [])
const getCalendarData = () => {
let eventsList = []
authAxios.get(url1).then((response) => {
if(response.status === 200)
{
response.data.map((course) => {
authAxios.get(url2).then((response) => {
if(response.status === 200)
{
response.data.map((assignment) => {
let startDate = new Date(Date.parse(assignment.due_at))
startDate.setUTCHours(0,0,0,0)
const endDate = new Date(Date.parse(assignment.due_at))
if(!Number.isNaN(endDate)) {
const event = {
title: assignment.name,
start: startDate,
end: endDate,
url: assignment.html_url,
}
if(!eventsList.includes(event)) { eventsList.push(event) }
}
})
}
})
})
}
})
return eventsList;
}
const locales = {
"nl-be": require("date-fns/locale/nl-be")
}
const localizer = dateFnsLocalizer({
format,
parse,
startOfWeek,
getDay,
locales
})
return (
<div className="calendarContainer" style={style}>
<h2 style={{"color":props.menuColour}}>Calendar</h2>
<div>
<Calendar
selectable
localizer={localizer}
events={calendarEvents}
startAccessor="start"
endAccessor="end"
style={{height: 500, margin: "50px"}}
/>
</div>
</div>
)
}
export default CalendarList;
getCalendarData should return a promise that resolves data. Your useEffect should call setEvents with the resolved data:
useEffect(() => {
getCalendarData().then((calendarData) => setEvents(calendarData));
}, []);
function getCalendarData() {
return authAxios.get(url1).then((response) => {
let eventsList = [];
// some logic
return eventList;
});
}