Implement complex requests declaratively, making the code more elegant

Scott Hu - Oct 30 '23 - - Dev Community

Traditional request tools such as axios, fetch function, etc. only provide the most basic request sending and receiving functions. However, in actual projects, requests do not exist alone. You may need to customize some implementations according to different request scenarios. Request logic, and maintenance of request-related status. Every time you encounter these slightly complex request scenarios, such as paging, form submission, sending verification codes, etc., you have to write a lot of code to solve it. After writing, there are still endless bugs.

Let’s recommend our request strategy library alovajs, which makes request and interface maintenance very simple.

what is alovajs

alovajs is a request strategy library, which means that it is specially used to handle various complex request scenarios. You only need to use the Hook which you need, and alovajs will help you automatically manage status, send requests, get response, etc. For example, in scenarios such as pagination, forms, and captcha, you can use extremely concise code to implement fully functional request logic!

Believe it or not, but I guarantee that alovajs is definitely a powerful tool to improve the elegance of your code! Please continue to look at some practical examples below.

Declarative requests of alovajs

Basic request

For example, to get a todo data, it is very simple to use the useRequest hook of alovajs:

// Parameter style similar to axios
const todoDetail = alova.Get('/todo', {
   params: {
     ID: 1
   }
});


const {
   loading,
   data,
   error,
   onSuccess,
   onError,
   onComplete,
   send,
   abort,
   update
} = useRequest(todoDetail);
Enter fullscreen mode Exit fullscreen mode

useRequest will automatically help you manage loading, data, error and other states, so you don’t need to maintain them by yourself.

useRequest documentation

Request when states change

In interactions such as data filtering and searching, you can use useWatcher to watch states changes and send request:

useWatcher(
   () => filterTodoList(page, keyword),
   [keyword, page],
   {
     debounce: [500, 0], // Request-level debounce params
   }
);
Enter fullscreen mode Exit fullscreen mode

It also has functions such as request debounce, ensuring request timing, filtering whether to send requests when the states changes, etc., which is super convenient!

useWatcher documentation

Prefetch data

You can use useFetcher to prefetch data. The relevant states will be updated:

const {
   fetching,
   error,
   fetch
} = useFetcher();
fetch(todoDetail);
Enter fullscreen mode Exit fullscreen mode

useFetcher documentation

Pagination request

In the pagination scenario, many states such as page, pageSize, pageCount, total, etc. need to be maintained by yourself, and a lot of logic must be written to determine when a request should be sent!

If you use the pagination Hook provided by alovajs, you only need this:

const {
   // loading status
   loading,

   // list data
   data,

   // Is it the last page?
   // When pulling down to load, you can use this parameter to determine whether it still needs to be loaded.
   isLastPage,

   //Current page number, changing this page number will automatically trigger the request
   page,

   //Number of data items per page
   pageSize,

   //Number of pagination pages
   pageCount,

   //Total amount of data
   total
} = usePagination((page, pageSize) => queryStudents(page, pageSize));

// Turn to the previous page, and the request will be automatically sent after the page value is changed.
const handlePrevPage = () => {
   page.value--;
};

// Turn to the next page, the request will be automatically sent after the page value changes
const handleNextPage = () => {
   page.value++;
};

//Change the number of pages per page. The request will be automatically sent after the pageSize value is changed.
const handleSetPageSize = () => {
   pageSize.value = 20;
};
Enter fullscreen mode Exit fullscreen mode

Isn’t it much cleaner and saves a lot of repeated code?

usePagination documentation

Form submission

Form function is also a headache, right? alova's useForm directly helps you with form submission, form drafts, automatic reset of form items, multi-step form, etc.

const {
   form,
   send: submitForm,
   updateForm
} = useForm(formData => submitData(formData), {
   initialForm: {
     title: '',
     content: '',
     time: '',
   },
   resetAfterSubmiting: true
});
Enter fullscreen mode Exit fullscreen mode

useForm documentation

Captcha

Stop making your own countdowns, this is it!

const {
   loading: sending,
   send: sendCaptcha
} = useCaptcha(() => sendCaptcha(mobile), {
   initialCountdown: 60
});
Enter fullscreen mode Exit fullscreen mode

useCaptcha documentation

Simpler file uploader

A simpler file upload strategy that supports automatic identification and conversion of base64, Blob, ArrayBuffer, and Canvas data. It can also upload multiple files at the same time and generate image previews.

const {
   fileList
   loading,
   progress
} = useUploader(({ file, name }) => uploadFile(file, name), {
   limit: 3,
   accept: ['png', 'jpg', 'gif'],
   imageTempLink: true
});
Enter fullscreen mode Exit fullscreen mode

useUploader documentation

Automatically re-pull data

The latest data can be pulled when the browser tab is switched, when the browser is focused, when the network is reconnected, and polling request. One or more of the above trigger conditions can be configured at the same time. You can also configure the throttle to prevent multiple requests from being triggered in a short period of time. For example, only one trigger is allowed within 1 second.

useAutoRequest(todoDetail, {
   enablePolling: 2000,
   enableVisibility: true,
   enableFocus: true,
   enableNetwork: true,
   throttle: 1000
}
Enter fullscreen mode Exit fullscreen mode

useAutoRequest documentation

Cross-component request strategy

Trigger request-related operations across components or modules, eliminate component-level restrictions, and quickly trigger any requested operation function in any component. For example, you can re-trigger the side menu bar after updating the menu data in a component. request to refresh the data. When the list data is manipulated, a list update is triggered.

// Component A creates an action delegation
useRequest(todoDetail, {
   middleware: actionDelegationMiddleware('someAction')
});

// Trigger delegation in component B
accessAction('someAction', (actions) => {
   actions.send()
});
Enter fullscreen mode Exit fullscreen mode

actionDelegationMiddleware documentation

Request retry strategy

Use it on important requests to improve the stability of the request. You can customize whether to retry, the retry delay, and manually stop retrying.

const {
   onRetry,
   onFail,
   stop,
} = useRetriableRequest(pay, {
   retry(error) {
     return /network timeout/i.test(error.message);
   },
   backoff: {
     delay: 2000
   }
});
Enter fullscreen mode Exit fullscreen mode

useRetriableRequest documentation

SSE

Requests can be made directly through SSE, which can automatically transform data through the function transformData of global responses and method instances, and also provides full control over the EventSource instance.

const {
   readyState,
   data,
   eventSource,
   onMessage,
   onError,
   onOpen,
   on
} = useSSE(() => chatGPT(), {
   withCredentials: true,
   interceptByGlobalResponded: true
});
Enter fullscreen mode Exit fullscreen mode

useSSE documentation

End

After using alova, I personally feel that alovajs is quite useful! It is an artifact that makes request development return to simplicity. Let's increase the efficiency and elegance of network requests!

There are many runnable examples here

If you think the article is helpful to you, please don't be stingy with your likes and comments. Tell me what you think of alovajs, or ask some questions. I will try my best to answer them. Your support is the biggest motivation for my creation! Hahahahahaha...

If you want to learn more about the usage of alovajs, welcome to alova document to learn. If you also like alovajs, please star it in Github repository, which is very important to us.

Welcome to join the communication community

If you have any questions, you can join the following communication, or you can publish Discussions in github repository. If you encounter any problems, please submit it in github issues and we will solve them as soon as possible.

At the same time, you are welcome to contribute, please go to Contributing guidelines.

. . . . . . . . . . . . . . . . . . . . . . . . .