Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeError: undefined is not an object (evaluating 'event.preventDefault') in ReactJS

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  // 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?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading