Dima Malko
Dima Malko

Reputation: 283

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.

Upvotes: 0

Views: 667

Answers (2)

vuongvu
vuongvu

Reputation: 829

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
}

Upvotes: 3

teckmk
teckmk

Reputation: 497

useEffect(() => {
    if (searchFromUrl) {
      handleSubmit(e); // u need to provide 'e'
    }
}, []);

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

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

Upvotes: 0

Related Questions