unicorn_surprise
unicorn_surprise

Reputation: 1109

Form onChange working, however fails to work when I change it to onSubmit?

I've been stuck trying to figure this out for ages. For some reason when the inputs onSubmit is set to onChange, it fires correctly. However I need it to be onSubmit, as I don't want it firing on every change. Does anyone know what I'm doing wrong and why the onSubmit isn't working for the input. I'm trying to set the state and update the URL query for something like:

"website.com/browse?country={text from input}"

const [countryQuery, setCountryQuery] = useQueryState("country", "")

const handleSubmitCountry = (e) => {
    e.preventDefault()
    setCountryQuery()
}

<form onSubmit={handleSubmitCountry}>
    <input 
        placeholder={countryQuery}
        type="text" 
        className={styles.searchInput}
        onSubmit={e => setCountryQuery(e.target.value)} 
    />      
</form>

Upvotes: 0

Views: 35

Answers (1)

Drew Reese
Drew Reese

Reputation: 202638

You need to extract the input's value from the form's onSubmit event in the handler using the input's name.

Don't attach any event handlers to the input element in order to leave it as an uncontrolled input, add a button/input to trigger the form onSubmit handler.

const handleSubmitCountry = e => {
  e.preventDefault();
  const countryQuery = e.target.countryQuery.value;
  // use countryQuery now
  countryQuery && alert(`Submitted Country Query: ${countryQuery}`);
};

...
<form onSubmit={handleSubmitCountry}>
  <input name="countryQuery" type="text" />
  <button type="submit">Submit</button>
</form>

Edit intelligent-cloud-6e0y9

Upvotes: 1

Related Questions