Search code examples
reactjstypescriptreact-hooksuse-effect

How to call function with event from useEffect


I have <form> with handleSubmit.

How do I call handleSubmit function with event from my useEffect?

useEffect(() => {
    if (searchFromUrl) {
      handleSubmit();
    }
  }, []);

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
}

<form onSubmit={handleSubmit} className="flex relative search-form"></form>

this is my error

 const handleSubmit: (e: React.FormEvent<HTMLFormElement>) => Promise<void>
    Expected 1 arguments, but got 0.ts(2554)
    SearchBox.tsx(27, 31): An argument for 'e' was not provided.

Solution

  • You're calling handleSubmit(); without having the e event variable.

    if you truly want to call it in useEffect, then change e argument to optional:

    const handleSubmit = async (e?: React.FormEvent<HTMLFormElement>) => {
      if (e) {
        e.preventDefault();
      }
      // do something
    }