Implement complex requests declaratively, making the code more elegant
Tags: javascript, axios, vue, react
Published: 2023-10-30 07:58:48

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!


- [alova official website](https://alova.js.org/) is here.

- If you also like alovajs, please star it in [Github repository](https://github.com/alovajs/alova). THAT is very important to us.

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:

```js
// 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);
```

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

[useRequest documentation](https://alova.js.org/tutorial/learning/use-request)

### Request when states change

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

```js
useWatcher(
   () => filterTodoList(page, keyword),
   [keyword, page],
   {
     debounce: [500, 0], // Request-level debounce params
   }
);
```

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](https://alova.js.org/tutorial/learning/use-watcher)

### Prefetch data

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

```js
const {
   fetching,
   error,
   fetch
} = useFetcher();
fetch(todoDetail);
```

[useFetcher documentation](https://alova.js.org/tutorial/learning/use-fetcher)


### 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:

```js
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;
};
```

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

[usePagination  documentation](https://alova.js.org/tutorial/strategy/usePagination)


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

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

[useForm documentation](https://alova.js.org/tutorial/strategy/useForm)


### Captcha

Stop making your own countdowns, this is it!
```js
const {
   loading: sending,
   send: sendCaptcha
} = useCaptcha(() => sendCaptcha(mobile), {
   initialCountdown: 60
});
```

[useCaptcha documentation](https://alova.js.org/tutorial/strategy/useCaptcha)


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

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

[useUploader documentation](https://alova.js.org/tutorial/strategy/useUploader)


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

```js
useAutoRequest(todoDetail, {
   enablePolling: 2000,
   enableVisibility: true,
   enableFocus: true,
   enableNetwork: true,
   throttle: 1000
}
```

[useAutoRequest documentation](https://alova.js.org/tutorial/strategy/useAutoRequest)


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

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

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

[actionDelegationMiddleware documentation](https://alova.js.org/tutorial/strategy/actionDelegationMiddleware)

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

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

[useRetriableRequest documentation](https://alova.js.org/tutorial/strategy/useRetriableRequest)


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

```js
const {
   readyState,
   data,
   eventSource,
   onMessage,
   onError,
   onOpen,
   on
} = useSSE(() => chatGPT(), {
   withCredentials: true,
   interceptByGlobalResponded: true
});
```

[useSSE documentation](https://alova.js.org/tutorial/strategy/useSSE)

## 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](https://alova.js.org/category/examples)

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](https://alova.js.org/) to learn. If you also like alovajs, please star it in [Github repository](https://github.com/alovajs/alova), 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](https://github.com/alovajs/alova/discussions). If you encounter any problems, please submit it in [github issues](https://github.com/alovajs/alova/issues) and we will solve them as soon as possible.

- [Join the Discord](https://discord.gg/S47QGJgkVb)

At the same time, you are welcome to contribute, please go to [Contributing guidelines](https://alova.js.org/contributing/overview).