Home > Software design >  Form onSubmit triggers even when submit button is not clicked
Form onSubmit triggers even when submit button is not clicked

Time:04-05

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:

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

CodePudding user response:

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.

  • Related