quick start of alovajs, a request strategy library
Tags: javascript, react, vue, svelte
Published: 2023-10-31 09:02:36

## What is alova

alova is a lightweight request strategy library that supports developers to implement complex requests such as request sharing, paging requests, form submissions, breakpoint uploads and others with declarative style code, allowing developers to implement high availability and high fluency request with less code, which means that you no longer need to rack your brains to write request optimization code, and no longer need to maintain request data and related status by yourself. You only need to select and use the request module, and set After setting the parameters, alova will do it for you. This improves development efficiency, application operation efficiency, and reduces server pressure.

## Install

```bash
# npm 
npm install alova --save

# yarn
yarn add alova
```

Alova combines the UI framework to make the request easier. You can use the **use hook** provided by alova to initiate a request, which will return stateful data related to multiple requests such as `loading`, and automatically manage it in alova them without having to maintain them yourself.

When using alova, please ensure that the UI framework meets the following version requirements:

1. React: >= v16.8
2. Vue: 2.7, 3.x
3. Svelte: Any

## Send a request using useRequest

First create an alova instance, use this instance to create the corresponding method, and pass it to useRequest.

### vue

```html
<template>
  <div v-if="loading">Loading...</div>
  <div v-else-if="error">{{ error. message }}</div>
  <span v-else>responseData: {{ data }}</span>
</template>

<script setup>
  import { createAlova, useRequest } from 'alova';
  import GlobalFetch from 'alova/GlobalFetch';
  import VueHook from 'alova/vue';

  // 1. Create an alova instance
  const alovaInstance = createAlova({
    // VueHook is used to create ref status, including request status loading, response data data, request error object error, etc.
    statesHook: VueHook,

    // request adapter, it is recommended to use the fetch request adapter
    requestAdapter: GlobalFetch(),

    // adapter GlobalFetch will return a Response instance
    // you can set a global response interception to return actual json data
    responded: response => response.json()
  });

  // 2. Use the alova instance to create a method and pass it to useRequest to send the request
  const { loading, data, error } = useRequest(
    alovaInstance.Get('https://api.alovajs.org/profile', {
      params: {
        id: 1
      }
    })
  );
</script>
```

### react

```jsx
import { createAlova, useRequest } from 'alova';
import GlobalFetch from 'alova/GlobalFetch';
import ReactHook from 'alova/react';

// 1. Create an alova instance
const alovaInstance = createAlova({
  // ReactHook is used to create ref status, including request status loading, response data data, request error object error, etc.
  statesHook: ReactHook,

  // request adapter, it is recommended to use the fetch request adapter
  requestAdapter: GlobalFetch()
});

const app = () => {
  // 2. Use the alova instance to create a method and pass it to useRequest to send the request
  const { loading, data, error } = useRequest(
    alovaInstance.Get('https://api.alovajs.org/profile', {
      params: {
        id: 1
      }
    })
  );

  if (loading) {
    return <div>Loading...</div>;
  } else if (error) {
    return <div>{error.message}</div>;
  }
  return (
    <>
      <span>responseData: {JSON.stringify(data)}</span>
    </>
  );
};
```

### svelte

```html
<script>
  import { createAlova, useRequest } from 'alova';
  import GlobalFetch from 'alova/GlobalFetch';
  import SvelteHook from 'alova/svelte';

  // 1. Create an alova instance
  const alovaInstance = createAlova({
    // SvelteHook is used to create ref status, including request status loading, response data data, request error object error, etc.
    statesHook: SvelteHook,

    // request adapter, it is recommended to use the fetch request adapter
    requestAdapter: GlobalFetch()
  });

  // 2. Use the alova instance to create a method and pass it to useRequest to send the request
  const { loading, data, error } = useRequest(
    alovaInstance.Get('https://api.alovajs.org/profile', {
      params: {
        id: 1
      }
    })
  );
</script>
{#if $loading}
<div>Loading...</div>
{:else if $error}
<div>{ $error. message }</div>
{:else}
<span>responseData: {{ data }}</span>
{/if}
```

## Request directly with method instance

The use hook can only be used to send requests within the component. Outside the component, you can directly send requests through the method instance.

```javascript
const response = await alovaInstance.Get('https://api.alovajs.org/profile?id=1').send();
```

For more information about method instance sending request, please go to [Use method instance to send request](https://alova.js.org/tutorial/next-step/send-request-directly) to read.

Regarding when to use useRequest to send a request and when to use a method instance to send a request, please read the [Best Practice](https://alova.js.org/tutorial/best-practice/skills) here.

## Used in static html

In addition to using esModule to install alova, you can also use `<script>` tags to use alova. example with vue3.

```html
<!DOCTYPE html>
<html lang="en">
  <head>
    <script src="https://unpkg.com/alova/dist/alova.umd.min.js"></script>
    <script src="https://unpkg.com/alova/dist/adapter/globalfetch.umd.min.js"></script>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <!-- vuehook depends on vue, so you need to introduce vue first -->
    <script src="https://unpkg.com/alova/dist/hooks/vuehook.umd.min.js"></script>
    <script>
      const alovaInstance = window.alova.createAlova({
        baseURL: 'https://api.alovajs.org',
        statesHook: window.VueHook,
        requestAdapter: window.GlobalFetch()
      });
      //...
    </script>
  </head>
  <body>
    <!-- ... -->
  </body>
</html>
```

## Other information of alovajs

### Why create alova?

Data requests have always been an essential part of applications. Since the birth of XMLHttpRequest, request schemes have emerged in an endless stream. Client data interaction exploration has always focused on the simplicity of requests, such as `$.ajax`, `axios`, `fetch api` and `react-query` and other request tools, the coding form is continuously developed from callback function, Promise, and then usehook. These js libraries have done a good job in request simplicity, but they only provide general functions, which means For different request scenarios such as sharing requests, paging requests, form submissions, uploading and downloading files, etc., developers still need to write complex codes themselves, which reduces development efficiency and performance cannot be guaranteed. In this era, application fluency has become more and more important.

**We believe that there are simpler solutions, such as using a use hook to get and manage paging data, manage form data, and implement brokenpoint continuingly-transferring, etc. That is use different request strategies in different request scenarios to efficiently implement the request function, so that developers can code less and achieve more efficient Client-Server data interaction. This is the solution we proposed and the mission of alova.**

### Reasons for choosing alova

Alova is also committed to solving the problem of client network requests, but unlike other request libraries, alova chooses the direction of business scenario request strategy, and it also provides rich Advanced Features.

- You may have been thinking about how to wrap `fetch` and `axios`. Now you no longer need to do this. alova complete complex requests with declarative style, such as request sharing, paging requests, form submissions, breakpoint uploads, etc, as well as automated cache management, request sharing, cross-component status update, etc.
- alova is lightweight, only 4kb+, which is 30%+ of axios.
- alova is low-coupling, you can make alova work with any UI framework in any js environment through different adapters (built-in supported UI framework is `vue/react/svelte`), and provides a unified experience and perfect code migration.
- alova can also achieve a highly aggregated organization of APIs. The request parameters, cache behavior, and response data transform of each API will be in the same code block, which has great advantages for managing a large number of APIs.

[For comparison with other request libraries](https://alova.js.org/tutorial/get-started/comparison)

## More framework support

Now, alova is available in [vue options (vue2 and vue3)](https://vuejs.org/guide/introduction.html#api-styles), [click here to view details](https://alova.js.org/tutorial/framework/vue-options). In the future, the following frameworks will be supported:

- Function style such as `solid/preact/qwik`.
- class style such as `angular/lit/stencil`.
- options style such as `native mini Program (China🇨🇳)`.

## End

[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).