yysun/apprun

How to avoid triggering components initial event handler on form submit?

jkleiser opened this issue · 2 comments

In the "Remote" component in my new SPA I have this form:

<form onsubmit={e => app.run("@get-host-games", state.host)}>
  <input type="text" autocapitalize="off" $bind="host" />
  <button class="btn">Get Games</button>
</form>

In the update list I also have this event handler:

"#Remote": (state, token) => {
  console.log("#Remote, token=%s", token);
  if (state.host.length > 0) {
    app.run("@get-host-games", state.host);
  }
  return { ...state, token };
}

When I enter something in the form's input and click the button, I see in the console that the "#Remote" event handler is also being called. The effect is that app.run("@get-host-games", state.host) is executed twice. It is not a big problem, but can I avoid the automatic call to the "#Remote" event handler in this situation?

Is it my use of onsubmit that triggers the "#Remote" event handler?

yysun commented

You can pass e to the event handler:

<form onsubmit={e => app.run("@get-host-games", state.host, e)}>
  ......
</form>

and then cancel it:

"#Remote": (state, token, e) => {
  e.preventDefault();
  ......
}

This is probably what you had in mind:

<form onsubmit={e => { e.preventDefault(); app.run("@get-host-games", state.host); }}>

It does what I wanted.
The added e in "#Remote": (state, token, e) => { seems always to be undefined.
Thanks.