DEV Community

Cover image for A new way to implement form submission
Scott Hu
Scott Hu

Posted on

A new way to implement form submission

A real form case

“Recently I am developing an ordering process for an e-commerce website. This ordering process is divided into multiple steps, from selecting the order products, to filling in the delivery address, to selecting the delivery method, etc.

At the beginning, I was still complacent, thinking that it was just form development and it should be very simple to do. Who knew that a multi-step form process would make me miserable.

The two biggest difficulties are:

  1. Each step corresponds to a component. How to share data between different components to ensure that the data can be connected in series.
  2. When the user refreshes the page in the middle step, all the information filled in is lost. How to avoid this.

I tried saving the form data to local storage, but it was very cumbersome to implement and I needed to manually maintain the storage and reading logic. When there are more pages, the complexity rises very high.

I originally planned to complete the form process in two days, but I have been struggling with it for a week and still haven't finished it. The project was so delayed that I almost got fired by my boss. "

The above is a true story of an alova user. Later he told me that he used alovajs's form hook to reconstruct it. He reconstructed the multi-step form process through the form hook, and it took only half a day to perfectly solve the data problem. When it comes to sharing and drafting, the speed is amazing.

alovajs form Hook

If you have also been tortured by form development, next I will introduce the form Hook of alovajs, be sure to read on!

The main advantages of alovajs' form Hook include:

  • Supports form drafts. The form data can also be restored by refreshing the page, so users do not need to refill it.
  • Can automatically reset the form, no longer need to reset the form items one by one
  • Multi-step forms can share data, solving the problem of data dependence between multiple forms
  • Supports conditional filtering forms, which can facilitate conditional filtering queries
  • Provides unified Hooks for submission status, response results, etc., easy to use
  • Only a few lines of code are needed to implement complex form logic, so you are no longer afraid of form scenarios.

Next let’s see how to use it!

Simple and easy to understand usage

The use of form Hook in alovajs is very simple. You can use the form Hook declaratively. You only need to pass in the submission function and configuration parameters. It will return the form data, submission status, event binding function and other necessary information related to the form, as follows It is a basic usage.

If you don’t understand the following case, you may need to read alova’s quick start to learn the basic usage of alova.

const {
   // Submit status
   loading: submitting,

   //Responsive form data, the content is determined by initialForm
   form,

   //Submit data function
   send: submit,

   // Submit successful callback binding
   onSuccess,

   //Submission failure callback binding
   onError,

   // Submit completion callback binding
   onComplete
} = useForm(
   formData => {
     // This function will be triggered when the form is submitted.
     // You can convert the form data here and submit it.
     return submitData(formData);
   },
   {
     //Initialize form data
     initialForm: {
       name: '',
       cls: '1'
     }
   }
);

//Submit form data
const handleSubmit = () => {
   // Validate form data...
   submit();
};
Enter fullscreen mode Exit fullscreen mode

Multi-step order form

We just mentioned the e-commerce order process. Now we will use this case to see how to use alovajs's form Hook to implement it.

The ordering process is divided into three steps: selecting the order product, selecting the address, and selecting the delivery method. The user's order data needs to be shared between different steps so that all form data can be accessed when submitting in the last step.

Select order items -> Select address -> Select delivery method

Enter fullscreen mode Exit fullscreen mode

In order to facilitate your understanding, I have made appropriate simplifications.

step 1

Initialize the form data and useForm configuration parameters in the first component, that is, the selection address, and set a unique id.

const { form, updateForm } = useForm(orderData => {
   return submitData(orderData);
}, {
   id: 'order'
   initialForm: {
     orderList: [], // Product list
     address: '', // Shipping address
     delivery: '' // delivery method
   },

   //Set this parameter to true to automatically reset the form data after submission is completed.
   resetAfterSubmiting: true,

   // Enable persistence to save data. After setting to true, unsubmitted data will be persisted in real time.
   store: true
});
Enter fullscreen mode Exit fullscreen mode

Step 2

In the next two components, form Hook is used in each component and the same id is passed in, so that the same form data, submission status, event binding function, etc. can be obtained.

// You can directly pass in the same id in the first parameter. The form obtained at this time is the same reference as the one in step 1.
const { form, send, updateForm, onSuccess, onError, onComplete } = useForm('order');
Enter fullscreen mode Exit fullscreen mode

Step 3

Within the last component, call send to submit the entire form data

Here is the sample code:

// You can directly pass in the same id in the first parameter. The form obtained at this time is the same reference as the one in step 1.
const {
   loading: submitting, // submission status
   form,
   send: submitForm
} = useForm('order');

//Submit the entire form
const handleSubmitBtnClick = () => {
   submitForm();
};
Enter fullscreen mode Exit fullscreen mode

By setting the same id, different components can share the same form data. And the form data will be automatically persisted without fear of being lost after refreshing.

In this way, a multi-step order process can be easily implemented.

End

As can be seen from this case, alovajs's form Hook has solved many pain points for us and greatly simplified form development.

If you have encountered similar form development difficulties, try alovajs!

I will continue to introduce more uses of alovajs in the future, so stay tuned.

alovajs also provides other powerful request strategies:

Multi-Framework Support

Now, you can perfectly use Alova in vue options (vue2 and vue3) syntax. In the future, we plan to support the following frameworks:

  • Functional ones like solid/preact/qwik.
  • Class-based ones like angular/lit/stencil.
  • Options-based ones like native Chinese mini-programs.

Alova also offers powerful request strategies:

Name Description Documentation
Pagination request strategy Automatically manage paging data, data preloading, reduce unnecessary data refresh, improve fluency by 300%, and reduce coding difficulty by 50% usePagination
Non-sense data interaction strategy A new interactive experience, submission and response, greatly reducing the impact of network fluctuations, allowing your application to still be available when the network is unstable or even disconnected useSQRequest
Form submission strategy A hook designed for form submission. Through this hook, you can easily implement form drafts and multi-page (multi-step) forms. In addition, it also provides common functions such as form reset useForm
File upload strategy A simpler file upload strategy that supports automatic identification and conversion of base64, Blob, ArrayBuffer, and Canvas data useUploader
Send verification code Verification code sending hook reduces the complexity of developing the verification code sending function. useCaptcha
Automatically re-pull data Automatically re-pull data under certain conditions to ensure that the latest data is always displayed. useAutoRequest
Trigger requests across components An alova middleware that eliminates component-level restrictions and quickly triggers the operation function of any request in any component actionDelegationMiddleware
UseRequest for serial requests A more concise and easy-to-use serial request use hook than alova's serial request method, providing a unified loading status, error, callback function useSerialRequest
UseWatcher for serial requests A more concise and easy-to-use serial request use hook than alova's serial request method, providing a unified loading status, error, callback function. useSerialWatcher
Request retry strategy Automatic retry on request failure, which plays an important role on important requests and polling requests useRetriableRequest
SSE requests Requests via Server-sent Events useSSE

For more in-depth learning about Alova, please visit the Alova documentation. If you find Alova helpful, please star on GitHub repository.

If you find this article helpful, don't hesitate to like and comment. Share your thoughts on Alova or ask any questions you may have. Your support is our greatest motivation!

Join Our Community

If you have any questions, you can join our community chat groups or start discussions on the GitHub repository. If you encounter any issues, please submit them on GitHub's issues page, and we will address them promptly.

We also welcome contributions. For more information, please visit our contribution guidelines.

Top comments (0)