Skip to main content
Version: v3

Combine UI framework

Next, we will learn how to use it in conjunction with the client UI framework, which can allow alova to exert its true power. When used in the UI framework, not only can alova automatically manage the responsive request status, but also automatically control when the request should be sent through certain rules.

alova provides 15+ client request strategies, which help you implement complex requests in a simple and elegant way. Let's continue to look down!

Set statesHook

Alova's useHook request strategy can run in all UI frameworks supported by Alova. You only need to set the statesHook of the corresponding UI framework on the Alova instance, which will tell Alova which UI framework should be used to create states.

import { createAlova } from 'alova';
import VueHook from 'alova/vue';

export const alovaInstance = createAlova({
// ...
statesHook: VueHook
});

In addition, alova also provides the following statesHooks:

Automatically manage request status

useRequest is our most commonly used request strategy. It can help us create and maintain responsive states of requests, such as loading/data/error, etc. You can use these responsive states directly in the view. When they change, the view will also change accordingly.

useRequest means sending a request. By default, a request will be sent when called.

<template>
  <div v-if="loading">Loading...</div>
  <div v-else-if="error">{{ error.message }}</div>
  <div v-else>
    <div>Request result: {{ data }}</div>
    <button @click="handleSend">Manually send request</button>
    <button @click="handleUpdate">Manually modify data</button>
  </div>
</template>

<script setup>
import { useRequest } from 'alova/client';
import { alovaInstance } from './api';

// Use the alova instance to create a method and pass it to useRequest to send a request
const { loading, data, error, send, update } = useRequest(
  alovaInstance.Get('/todos/1', {
    cacheFor: 0
  }),
  {
    initialData: {}, // Set the initial data of the data state
    immediate: true // Whether to send a request immediately, the default is true
  }
).onSuccess(event => {
  event.method; //The method of the current request
  event.data; //Response data of the current request
});

const handleSend = () => {
  send();
};
const handleUpdate = () => {
  update({
    data: { title: 'new title' }
  });

  // You can also modify the data value directly
  // data.value = { title: 'new title' };
};
</script>

When to use useRequest and when to send a request via await alovaInstance.Get.

useHook usage specification

Please note that useRequest can only be used to send requests within a component. Outside a component, you can send requests directly through a method instance, and the use of useRequest must comply with the use hook usage rules, that is, it can only be called at the outermost level of a function.

❌❌❌ It is not recommended to call it in a loop, conditional judgment, or sub-function. For example, the following example of use in a click callback, when used in a callback function, although the request can be initiated normally, the responsive data returned by the use hook cannot be used in the view, and the same is true for loops and conditional judgments.

// ❌ bad
const handleClick = () => {
const { loading, data } = useRequest(getter);
};

// -------
// ✅ good
const { loading, data, send } = useRequest(getter, {
immediate: false
});
const handleClick = () => {
send();
};

Submit data

When you need to submit a new todo item, you can first turn off the default send request, switch to manual trigger request, and receive the send function in useRequest for manual request sending. The send function will return a Promise instance with response data, which will be changed to resolve state after the request response.

At this time, in order to receive the parameters passed in by the send function, you can set the first parameter of useRequest to a function, which we call method handler.

const {
// ...
// Function for manual sender request, send request after calling
send: addTodo

// Parameters of send function will be received here
} = useRequest(newTodo => alovaInstance.Post('/todo', newTodo), {
// When immediate is false, it is not sent by default
immediate: false
});

// Send request manually
const handleAddTodo = () => {
const newTodo = {
title: 'New todo item',
time: new Date().toLocaleString()
};
// The send function returns a Promise object, which can receive response data
addTodo(newTodo)
.then(result => {
console.log('Add todo item successfully, response data is:', result);
})
.catch(error => {
console.log('Add todo item failed, error message is:', error);
});
};

The send function allows you to freely repeat requests.

In react, the send function uses the useCallback package, and it is not restricted by the closure trap. You can use it directly in the event without worrying about performance problems.

Process Response

After the request is completed, the response data will be processed through multiple processes before the final data is obtained at the location where the request was sent. The process is as follows:

When no error is thrown, the next node receives the return value of the previous node.

Transform response data

In method detailed explanation, we have already learned about transform, which is also very useful when used in useHook. It allows useHook's data to receive the transformed data without transform again.

const todoListGetter = alovaInstance.Get('/todo/list', {
// The function accepts raw data and response header objects, and requires the transformed data to be returned, which will be assigned to the data state.
// Note: rawData is the data filtered by the global response interceptor (if it is set). For the configuration of the response interceptor, please refer to the [Setting the Global Response Interceptor] chapter.
transform(rawData, headers) {
return rawData.list.map(item => ({
...item,
statusText: item.done ? 'Completed' : 'In progress'
});
}
});
const { data } = useRequest(todoListGetter);
const { data } = useWatcher(() => todoListGetter, [userInfo]);

The data value will receive the transformed data format.

type data = {
// ...
statusText: 'Completed' | 'In progress';
}[];
note

When used in usehooks, throwing an error in transform will also trigger onError;

Bind response callback

If you need to set a request callback, you can also receive the callback setting function in the return parameter of useHooks, as follows:

const {
// ...

//Successful callback binding
onSuccess,

// Failure callback binding
onError,

// Complete the callback binding, the callback will be called on success or failure
onComplete
} = useRequest(todoListGetter);
onSuccess(event => {
console.log('The request was successful, the response data is:', event.data);
console.log('The method instance of this request is:', event.method);
console.log('Whether the response data comes from the cache:', event.fromCache);
});
onError(event => {
console.log('The request failed, the error message is:', event.error);
console.log('The method instance of this request is:', event.method);
});
onComplete(event => {
// event.status is success when it succeeds and error when it fails.
console.log('The request is completed, the status is: ', event.status);
console.log('The method instance of this request is:', event.method);
console.log('Whether the response data comes from the cache:', event.fromCache);
if (event.data) {
console.log('Request data:', event.data);
} else if (event.error) {
console.log('Error message:', event.error);
}
});

We also support the chain call of binding functions in all useHooks。

const { data, loading, error, onSuccess, onError, onComplete } = useRequest(todoListGetter)
.onSuccess(event => {
// ...
})
.onError(event => {
// ...
})
.onComplete(event => {
// ...
});
Hint

Throwing an error in onSuccess will trigger onError.

End

The above is the basic use of our most commonly used useRequest. Other commonly used request strategies include:

  1. useWatcher: monitor data changes and automatically request
  2. useForm: form data submission and management
  3. useAutoRequest: automatically request according to rules such as timed polling, browser focus, network reconnection, etc.
  4. ...

For complete usage or other client request strategies, please move to Client Strategy to view all client request strategies provided by alova.