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

Form onSubmit triggers even when submit button is not clicked

I have a section with different fields etc. which are basically just parameters for when I need to fetch data.

So basically the structure is something like this:

<form onSubmit={fetchData}>
   some parameter fields
</form>

For example, one of the parameters that can be changed is the date, which I can do by de- or increasing the date from today by one day, e.g:

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

<button onClick={decreaseDate}>
  -
</button>
<input
  type="number"
  max="1"
  value={incrementDate}
  onChange={onChangeDate}
/>
<button onClick={increaseDate}>
  +
</button>

where:

const [incrementDate, setIncrementDate] = useState(0);

const increaseDate = () => {
  setIncrementDate(incrementDate + 1);
};

const decreaseDate = () => {
  setIncrementDate(incrementDate - 1);
};

const onChangeDate = ({ target }) => {
  const { value } = target;

  const attemptedParse = parseInt(value);

  if (!Object.is(NaN, attemptedParse)) {
    setIncrementDate(attemptedParse);
  }
};

So basically this changes the date for the data that needs to be fetched when I click the submit button:

<button type="submit">
  Get data
</button>

As far as I get can see the fetchData function is not called other than in the onSubmit of the form. However, the issue is, that whenever I click decrease or increase new data is fetched with the new date value. So instead of me needing to click the submit button, it just fetches new data automatically. And this is not intended in this case. I would really just like it to fetch new data whenever I click the submit button.

Am I doing something wrong here, or…?

>Solution :

Here is the simple fix :

    <button type="button" onClick={decreaseDate}>
      -
    </button>
    <input type="number" max="1" value={incrementDate} onChange={onChangeDate}/>

    <button type="button" onClick={increaseDate}>
      +
    </button>

let me know if it works.

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