I am new to react and I need to update the update the state variable in a function every time a function is rendered. This variable is used as a prop to a component.
The code is,
function Cal(props) {
const [allEvents, setEvents] = useState({ events: [] });
const [currentYear, setCurrentYear] =useState(moment().year().toString());
useEffect(() => {
getEvents();
}, [currentYear]);
async function getEvents() {
const yearStart = `${currentYear}-01-01`;
const yearEnd = `${currentYear}-12-31`;
const data = await fetchEvents(yearStart, yearEnd, 'Discount', currentLang);
console.log('data:', data);
setEvents(data);
console.log('allEvents:', allEvents);
}
return (
<ChildComp
eventData={allEvents}
/>
);
}
UPDATE: I need the function getEvents to be called every time the value of current year is changed.When I console log the value of data, I see the response data. But when I console log allEvents, I always see an empty array. I don't see the value of data updated. ? Any help would be appreciated.
Thanks