Transform response of alovajs, a request strategy library
Tags: javascript, react, vue, svelte
Published: 2023-11-22 05:46:04

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

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](https://github.com/alovajs/alova).

## Join Our Community

If you have any questions or need assistance, you can join our communication or start a discussion on [GitHub repository](https://github.com/alovajs/alova/discussions) for support. If you encounter any issues, please submit them on [GitHub issues](https://github.com/alovajs/alova/issues), and we'll address them as soon as possible.

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

We also welcome contributions. For more information, please visit [contribution guidelines](https://alova.js.org/contributing/overview).

> For tutorials and more on how to use Alova, feel free to explore the [alova documentation](https://alova.js.org/).


## Transform response data

When the response data structure cannot directly meet the front-end requirements, we can set the `transformData` hook function for the method instance to convert the response data into the required structure, and the data will be used as the value of the `data` state after conversion.

```javascript
const todoListGetter = alovaInstance.Get('/todo/list', {
  params: {
    page: 1
  },

  // The function accepts raw data and response header objects, and asks to return the converted data, which will be assigned to the data state.
  // Note: rawData is generally the data filtered by the response interceptor. For the configuration of the response interceptor, please refer to the [Setting the Global Response Interceptor] chapter.
  transformData(rawData, headers) {
    return rawData.list.map(item => {
      return {
        ...item,
        statusText: item.done ? 'completed' : 'in progress'
      };
    });
  }
});
```

> Note: 
> 1. When used in usehooks, throwing an error in `transformData` will trigger `onError`;
> 2. When sent a request by method instance, a rejected promise instance will be returned;

### special usage of transformData

Since the transformData function has the following two properties:

1. It will only be triggered when the network request responds, and will not be triggered when the response cache is hit;
2. Support asynchronous functions;

You can also use it as a hook function for network request response. For example, in the cache scenario where files are used as response data, you can cooperate with IndexedDB to cache file data, and at the same time cooperate with [Controlled cache](https://alova.js.org/tutorial/next-step/controlled-cache) to hit the file cache in IndexedDB.

```javascript
const fileGetter = alovaInstance.Get('/file/file_name', {
  // Use IndexedDB to cache files
  async transformData(fileBlob) {
    await new Promise((resolve, reject) => {
      const tx = db.transaction(['files'], 'readwrite');
      const putRequest = tx.objectStore('files').put({
        file: fileBlob
      });
      putRequest.onsuccess = resolve;
      putRequest.onerror = reject;
    });
    return fileBlob;
  }
});
```

## (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](https://alova.js.org/tutorial/get-started/comparison)

## Multi-Framework Support

Now, you can perfectly use Alova in [vue options (vue2 and vue3) syntax](https://vuejs.org/guide/introduction.html#api-styles). 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](https://alova.js.org/tutorial/strategy/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](https://alova.js.org/tutorial/strategy/sensorless-data-interaction/overview)     |
| 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](https://alova.js.org/tutorial/strategy/useForm)                                       |
| File upload strategy                | A simpler file upload strategy that supports automatic identification and conversion of base64, Blob, ArrayBuffer, and Canvas data                                                                                 | [useUploader](https://alova.js.org/tutorial/strategy/useUploader)                               |
| Send verification code              | Verification code sending hook reduces the complexity of developing the verification code sending function.                                                                                                        | [useCaptcha](https://alova.js.org/tutorial/strategy/useCaptcha)                                 |
| Automatically re-pull data          | Automatically re-pull data under certain conditions to ensure that the latest data is always displayed.                                                                                                            | [useAutoRequest](https://alova.js.org/tutorial/strategy/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](https://alova.js.org/tutorial/strategy/actionDelegationMiddleware) |
| UseRequest for serial requests      | A more concise and easy-to-use serial request use hook than [alova's serial request method](https://alova.js.org/tutorial/next-step/serial-request), providing a unified loading status, error, callback function  | [useSerialRequest](https://alova.js.org/tutorial/strategy/useSerialRequest)                     |
| UseWatcher for serial requests      | A more concise and easy-to-use serial request use hook than [alova's serial request method](https://alova.js.org/tutorial/next-step/serial-request), providing a unified loading status, error, callback function. | [useSerialWatcher](https://alova.js.org/tutorial/strategy/useSerialWatcher)                     |
| Request retry strategy              | Automatic retry on request failure, which plays an important role on important requests and polling requests                                                                                                       | [useRetriableRequest](https://alova.js.org/tutorial/strategy/useRetriableRequest)               |
| SSE requests                        | Requests via Server-sent Events                                                                                                                                                                                    | [useSSE](https://alova.js.org/tutorial/strategy/useSSE)                                         |

For more in-depth learning about Alova, please visit the [Alova documentation](https://alova.js.org/). If you find Alova helpful, please star on [GitHub repository](https://github.com/alovajs/alova).

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](https://github.com/alovajs/alova/discussions). If you encounter any issues, please submit them on [GitHub's issues page](https://github.com/alovajs/alova/issues), and we will address them promptly.

- [Join our Discord community for discussions](https://discord.gg/S47QGJgkVb)

We also welcome contributions. For more information, please visit our [contribution guidelines](https://alova.js.org/contributing/overview).