Hope you’re all good.
I’m having an issue I can’t find a concise answer on so I’m going to ask for help here.
I have a function which I’m trying to call in my React Component:
// Open up calendar day if today is equal to day in API.
const [openCalendarBox, setOpenCalendarBox] = useState('');
// Call on post method via axios
const openCalendarChocolateBox = async (event) => {
event.preventDefault();
if (date) {
// Url where to post
await axios.post(`http://localhost:5001/open/chocolate`, {
day: date,
});
alert('New day is available to eat!');
}
setOpenCalendarBox('');
};
openCalendarChocolateBox();
But when I call the function it doesn’t work like it’s suppose to, I’m instead getting this error in the console:
Unhandled Promise Rejection: TypeError: undefined is not an object (evaluating 'event.preventDefault')
How do I solve this issue? I tried removing the event parameter in my argument but I still want to prevent the page from reloading more than once or at all when calling on my function.
Thanks for any help in advance, take care guys.
>Solution :
If you want to load this when the component loads, you don’t need an event listener. Simply move the code to a useEffect() hook with an empty dependency array (will only run when component loads).
useEffect(() => {
if (date) {
// Url where to post
await axios.post(`http://localhost:5001/open/chocolate`, {
day: date,
});
alert('New day is available to eat!');
}
setOpenCalendarBox('');
}, [])
New problem though, where is date coming from?