Quick Qwik tip — Form submit

Ran Wahle
Israeli Tech Radar
Published in
2 min readDec 29, 2022
Qwik Logo

Just before we begin, a little disclaimer. I’m writing this story while Qwik is in the beta stage and could be subjected to breaking changes, therefore, this article is updated to its publishing time.

Preface: What is Qwik?

Qwik is an HTML-first framework, meaning that it downloads your javascript just in time you need it.

OK, What could go wrong with form submission?

Well, on the traditional, and very old websites, whenever you submitted a form, it fully reloaded its content by default, and on SPA, you should have handled the form onSubmit event in order to prevent that behavior.
However, when you wanted to have the exact approach in Qwik, you didn’t have your javascript loaded. Therefore, when the user submits the form, it doesn’t know (yet) that it has an onSubmit event handler so it wouldn’t use it.
I’ve tried writing <form onSubmit={() => mySubmitEventHandler()}> and failed, maybe because of that.

UseClientEffect$ and useOn to the rescue

Before explaining what useOn… does, let’s remember our plain old addEventListener method.

The two lines of code above must run on the client side, of course, we may, of course, use useClientEffect$ hook

One other approach is making sure where this code runs, using useOn hook, and making sure that the needed javascript is downloaded only after real interaction.

Please note, using the useOn hook is on the element being rendered, the event here we listen to is the keydown event which can run several times, in order to run it once you may use the useOnDocument hook that has events such as load, and DOMContentLoaded which runs only once on the client side.

OK, what is the difference between the two?

Well, actually, a lot. The main difference is that useClientEffect$ runs its callback function once, on the client, and then it sets its event listeners that will run every time events will occur. While the useOn (on the component, and, of course, useOnDocument, and useOnWindow on the document element or on the window element respectively), runs their callback every time the event given at their first parameter, occurs, and it may also run on the server.

What should I use?

Actually, both are good, however, using useClientEffect$ will be for client code only, and it involves some code overhead, and maybe, if the element is not rendered on the client, an error will occur, while useOn-* is less error prune.

--

--