DEV Community

Cover image for Data prefetch of alovajs, a request strategy library
Scott Hu
Scott Hu

Posted on

Data prefetch of alovajs, a request strategy library

Alova is a lightweight request strategy library designed to simplify interface management and usage. It consists of 2 parts:

  1. Declarative implementation of complex requests: You can implement complex requests such as request sharing, pagination, form submission, breakpoint resume, etc. by simply configuring parameters without writing a lot of code, improving development efficiency and application performance and reduce pressure on the server.

  2. API automatic management and maintenance: You no longer need to define the request functions by yourself, and you no longer need to consult the API documentation. alova can help you generate a complete and detailed TypeScript type of the request function, so that the front-end project can be integrated with the server-side seamless. When the server-side API is updated, the front-end project will also be notified and the project will be blocked from publishing.

There are many runnable examples here

With Alova, all you need to do is select the appropriate useHook for your requests, now it support React, Vue, and Svelte. If you find alova helpful, please consider star on GitHub repository.

Join Our Community

If you have any questions or need assistance, you can join our communication or start a discussion on GitHub repository for support. If you encounter any issues, please submit them on GitHub issues, and we'll address them as soon as possible.

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

For tutorials and more on how to use Alova, feel free to explore the alova documentation.

Data fetch

When you have the following needs:

  1. Preload the data that will be used in the subsequent process and store it in the cache, so that users no longer wait for the data loading process;
  2. It is convenient to update data across pages (similar to the global state), for example, after modifying an item in the todo list and re-fetching the latest data, the interface will be refreshed after the response.

useFetcher is the hook used to implement the above scenarios. The response data obtained through it cannot be received directly, but the data fetched through it will not only update the cache, but also update the corresponding state, thereby re-rendering the view.

You can use it to pre-fetch data and save it in the cache, or gracefully update the state across components, such as modifying an item in the todo list and re-fetching the latest data, and the interface will be refreshed after the response

the following code is used react.

Update views across modules/components

Next, let's modify a certain todo data, and re-fetch the latest todo list data to update the view.

const getTodoList = currentPage => {
  return alovaInstance.Get('/todo/list', {
    // Note: The name attribute is set here to filter out the required Method instance when the Method instance cannot be specified directly
    // For details, see the subsequent "Method Instance Matcher" chapter
    name: 'todoList',
    params: {
      currentPage,
      pageSize: 10
    }
  });
};

const App = () => {
  const {
    // The fetching attribute is the same as loading, it is true when a fetch request is sent, and it is false after the request ends
    fetching,
    error,
    onSuccess,
    onError,
    onComplete,

    // After calling fetch, a request to fetch data will be sent, and fetch can be called repeatedly to fetch data from different interfaces
    fetch
  } = useFetcher();

  // Trigger the data fetch in the event
  const handleSubmit = () => {
    // Assume the modification of the todo item has been completed...

    // Start to fetch the updated data
    // Situation 1: When you clearly know that the data on the first page of todoList is fetched, pass in a Method instance
    fetch(getTodoList(1));

    // Situation 2: When you only know to fetch the last requested data of todoList, use the Method instance matcher to filter
    fetch({
      name: 'todoList',
      filter: (method, index, ary) => {
        // Return true to specify the Method instance that needs to be fetched
        return index === ary.length - 1;
      }
    });
  };

  return (
    <>
      {/* Render the unified fetch state */}
      {fetching ? <div>Fetching data in the background...</div> : null}
      {/* ... */}
      <button onClick={handleSubmit}>Modify todo items</button>
    </>
  );
};
Enter fullscreen mode Exit fullscreen mode

See Method instance matcher for more usage methods of Method instance matcher

preload data

The following implements the preloading function of the next page of data in the paging scenario of the todo list.

import { useState } from 'react';

// method instance creation function
const getTodoList = currentPage => {
  return alovaInstance.Get('/todo/list', {
    params: {
      currentPage,
      pageSize: 10
    }
  });
};

const App = () => {
  const { fetch } = useFetcher();
  const [currentPage, setCurrentPage] = useState(1);
  const { data, onSuccess } = useWatcher(() => getTodoList(currentPage), [currentPage], {
    immediate: true
  });

  // Pre-fetch the data of the next page when the current page request is successful
  // Realize that there is no need to wait for the request when turning the page to the next page
  onSuccess(() => {
    fetch(getTodoList(currentPage + 1));
  });

  return {
    /* ... */
  };
};
Enter fullscreen mode Exit fullscreen mode

Notes: After the useFetcher request is completed, only the cache is updated, and if it is found that there is still a data state under the Method instance, it will also be updated synchronously, so as to ensure that the page data is consistent. This is useFetcher used to update views across modules/components ensure.

Compare with useRequest and useWatcher

  1. useFetcher does not return the data field, the pre-fetched data will be saved in the cache, and the status data of the corresponding location will be updated;
  2. Rename loading to fetching;
  3. There is no send function, but there is a fetch function, which can be reused to fetch data from different interfaces. At this time, you can use the fetching and error states to render views uniformly, so as to achieve unified processing the goal of;

(End)Why Use Alova

Alova is committed to addressing client-side network request challenges, but what sets it apart from other request libraries is its focus on business-scenario-driven request strategies. When used in conjunction with libraries like axios/fetch api, Alova can meet 99% of your request needs while offering a range of advanced features.

  • You may have pondered over whether to encapsulate fetch and axios, but now you no longer need to. With Alova, you can use a declarative approach to fulfill complex requests, including request sharing, pagination, form submissions, and resumable uploads, as well as automated cache management, request sharing, and cross-component state updates.

  • Alova is lightweight, occupying only 4kb+, which is just over 30% of Axios's size.

  • It currently supports vue/react/react-native/svelte and SSR frameworks like next/nuxt/sveltekit, as well as cross-platform frameworks like Uniapp/Taro.

  • Alova is loosely coupled, allowing you to use it in any JavaScript environment with any UI framework using different adapters. It offers a unified user experience and seamless code migration.

  • Alova also promotes a highly organized approach for aggregating API code, grouping request parameters, cache behavior, and response data transformations in the same code blocks, which is advantageous for managing numerous APIs.

Compare Alova with other request libraries

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)