Alova is coming, are you still using axios?

Scott Hu - Nov 15 '23 - - Dev Community

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 is here.

If you also like alovajs, please contribute a star in Github repository, 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.

<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>
Enter fullscreen mode Exit fullscreen mode

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

useRequest detailed documentation

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.

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

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

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:

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

useFetcher detailed documentation

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:

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 detailed documentation

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.

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

useForm detailed documentation

Verification code implementation

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 detailed documentation

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.

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 detailed documentation

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.

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

useAutoRequest detailed 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 a proxy
useRequest(todoDetail, {
   middleware: actionDelegationMiddleware("someAction"),
});

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

actionDelegationMiddleware detailed 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 detailed documentation

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.

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

useSSE detailed documentation

end

Now, you can also use alova in the options writing method of vue2, click to view details

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 official website to learn. If you also like alovajs, please contribute a star 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 group chat for consultation, or you can publish Discussions in github repository. If you encounter problems, please also post in github issues and we will solve it as soon as possible.

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

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