Alova is coming, are you still using axios?
Tags: vue, react, svelte, alova
Published: 2023-11-15 03:49:27

Hello, I am Scott.

Today, I want to talk something that when we write project code, we should focus more on the implementation of business logic, and hand over the fixed code to the js library or engineering for automatic processing. What I want to say is that the request logic can actually continue simplified.

You may say that using `axios` or `fetch api` is enough. There is no request logic. That may be because you are not aware of this problem. As a front-end developer, you must have encountered these problems:

- Handle paging logic.
- Form processing logic.
- Process request debounce logic.
- Handle polling checks.
- Handle cache handling.
- Handle loading status.
- Handle error handling.
- Captcha sent.
- File Upload.
-...

These problems, if you are using `axios` or `fetch api`, you need to write a lot of code to deal with these problems, but I want to say that they are actually more fixed template codes and can also be streamlined.

Today you can use `alova` to handle them. `alova` provides a large number of request modules commonly used in daily business. You only need to simply configure a few lines of code, and `alova` can automatically help you manage the request status, optimize the network experience, and eliminate those annoying paging logic. , polling check, cache processing, all of which you don’t have to worry about, allowing you to focus more on business logic.

## alova’s learning cost is lower

alova draws on the design of axios and ahooks-useRequest, making it easier for everyone to get started and with lower learning costs.

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

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

Let's take a look at how simple configuration can help you solve request problems in various complex scenarios.

## Basic request

Basic request, suitable for initialization information, comes with various statuses related to the request.

Take vue3 as an example.

```html
<template>
   <div>
     <div v-if="loading">loading...</div>
     <div v-else-if="error">error: {{ error }}</div>
     <div v-else>
       <div>
         <span>id: {{ data.title }}</span>
         <span>title: {{ data.time }}</span>
       </div>
     </div>
   </div>
</template>

<script setup>
   import { useRequest } from "alova";

   // 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);
   onSuccess((event) => {
     console.log("success", event);
   });
   onError((event) => {
     console.log("error", event);
   });
   onComplete((event) => {
     console.log("complete", event);
   });
</script>
```

useRequest will automatically help you manage loading, data, error and other states, so you don’t need to control it yourself!

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

## Status change request

In interactions such as data filtering and search, you can use useWatcher to monitor state changes and send requests. The return value also contains the same state, event function, and operation function as useRequest.

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

It also has functions such as requesting anti-shake, ensuring request timing, filtering whether to send requests when the status changes, etc., which is super convenient!

[useWatcher detailed documentation](https://alova.js.org/tutorial/learning/use-watcher)

## Preload data

You can use useFetcher to preload data. There is no need to directly process the response, but the relevant status will be updated:

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

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

## Pagination request

In the paging 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 paging 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 detailed documentation](https://alova.js.org/tutorial/strategy/usePagination)

## Form submission

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

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

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

## Verification code implementation

Stop making your own countdowns, this is it!

```js
const { loading: sending, send: sendCaptcha } = useCaptcha(
   () => sendCaptcha(mobile),
   {
     initialCountdown: 60,
   }
);
```

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

## File upload strategy

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 detailed documentation](https://alova.js.org/tutorial/strategy/useUploader)

## Automatically re-pull data

The latest data can be pulled when the browser tab is switched, the latest data can be pulled when the browser is focused, the latest data can be pulled when the network is reconnected, and the data can be automatically re-pulled by polling request. One or more of the above trigger conditions can be configured at the same time. , you can also configure the throttling time 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 detailed 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 a proxy
useRequest(todoDetail, {
   middleware: actionDelegationMiddleware("someAction"),
});

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

[actionDelegationMiddleware detailed 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 detailed documentation](https://alova.js.org/tutorial/strategy/useRetriableRequest)

## SSE

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

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

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

# end

Now, you can also use alova in the options writing method of vue2, [click to view details](https://alova.js.org/tutorial/framework/vue-options)

[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 official website](https://alova.js.org/) to learn. If you also like alovajs, please contribute a star 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 group chat for consultation, or you can publish Discussions in [github repository](https://github.com/alovajs/alova/discussions). If you encounter problems, please also post in [github issues ](https://github.com/alovajs/alova/issues) and we will solve it as soon as possible.

- [Join the Discord community to participate in communication](https://discord.gg/S47QGJgkVb)

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