Introduce
What is alova?
Alova (pronounced /əˈləʊva/
) is a next-generation request library that radically simplifies your API integration workflow, reducing what used to take 7 complex steps down to just 1 - simply select your API and go.
Unlike libraries such as @tanstack/react-request
, swrjs
, and useRequest
from ahooks
, alova revolutionizes your development experience by wrapping fetch/XMLHttpRequest/axios
into request adapters and providing intelligent request strategies for even the most complex scenarios.
Want to dive into the origin story? Check out Why we created alova. For a deep dive into how we're different, explore our comprehensive comparison with other request libraries.
Features
- Incredibly simple to use with a minimal learning curve.
- More modern OpenAPI solution - say goodbye to tedious intermediate API documentation.
- Compatible with client-side technologies and request libraries:
react/vue/svelte/solid/next/nuxt/sveltkit/solid-start/uniapp/taro/...
+fetch/XMLHttpRequest/axios/...
- Compatible with server-side technologies and request libraries:
nodejs/deno/bun/...
+fetch/XMLHttpRequest/axios/...
- 15+ high-performance request strategies to handle complex request scenarios, helping you develop more efficient applications faster.
Live Demo
We've prepared a rich set of examples to help you quickly explore alova's capabilities.
How It Works?
alova provides comprehensive solutions for complex request scenarios, which we call Request Strategy , encompassing both client-side and server-side request strategies.
Client request strategy
On the client-side, request strategies are implemented through hooks, interceptors, and middleware, allowing you to tackle different request scenarios with precision. These strategies provide comprehensive, stateful parameters, events, and operational functions for every request scenario, enabling you to implement complex request logic with just a single line of code. Not only do they boost your development efficiency, but they also optimize your app's performance and reduce server-side load.
Below are introductions and examples of some client-side request strategies. Feel free to explore the ones that catch your interest.
Watching request strategy
The Watching request strategy is used in scenarios where re-requests are made as data changes, such as fuzzy search, tab bar switching, etc.
const {
// Responsive states
loading,
error,
data,
// Events
onSuccess,
onError,
onComplete,
// actions
send,
update
// ...
} = useWatcher(
() =>
alova.Get('/api/user', {
params: {
type: activeTab
}
}),
[activeTab]
);
See Watcher Request Strategy for details.
Pagination request strategy
The pagination request strategy helps you quickly implement comprehensive paging data request scenarios, including page turning, conditional query, pre-fetching of next page data, insert/replac/remov data items, refresh and reset list.
const {
// Responsive states
loading,
error,
data,
page,
pageSize,
total,
// Events
onSuccess,
onFetchSuccess,
onError,
onFetchError,
// Actions
refresh,
insert,
replace,
remove,
reload,
send,
abort,
update
// ...
} = usePagination(
(page, size) =>
alova.Get('/api/user/list', {
params: { page, size }
}),
{
preloadNextPage: true,
watchingStates: [username, sex],
debounce: 500
}
);
See Pagination Request Strategy for details.
Token authentication strategy
Token authentication strategy provides global interceptors that can help you maintain all the codes of token authentication, including login, logout, token attachment, token refresh, etc., and supports seamless token refresh.
const { onAuthRequired, onResponseRefreshToken } = createServerTokenAuthentication({
refreshTokenOnError: {
isExpired: res => res.status === 401,
refrshTokenOnError: async () => {
const { token, refresh_token } = await refreshToken();
localStorage.setItem('token', token);
localStorage.setItem('refresh_token', refresh_token);
}
}
});
const alovaInstance = createAlova({
beforeRequest: onAuthRequired(),
responded: onResponseRefreshToken()
});
See Token Authentication Interceptor for details.
Form submission strategy
Through the form submission strategy, you can quickly implement form drafts and multi-page (multi-step) forms. In addition, it also provides common functions such as form reset.
const {
// Responsive states
loading: submiting,
error,
form,
// Events
onSuccess,
onError,
onComplete,
// Actions
send: submit,
updateForm,
abort
// ...
} = useForm(formData => alova.Post('/user/profile', formData), {
initialForm: {
name: '',
age: '',
avatar: null
},
resetAfterSubmiting: true,
store: true
});
See Form Submission Strategy for details.
Data Fetching Strategy
By fetching necessary data in advance, users no longer need to wait for the data to load, thus improving the user experience.
const {
// Response states
loading,
error,
// Events
onSuccess,
onError,
onComplete,
// actions
fetch,
update,
abort
// ...
} = useFetcher();
const handleItemClick = itemId => {
fetch(
alova.Get('/ api/user/detail', {
params: {
id: itemId
}
})
);
};
See Data Fetching Strategy for details.
Seamless Data interaction Strategy
Seamless data interaction means that when users interact with an application, relevant content can be displayed immediately without waiting, or the results of operations can be displayed without waiting when submitting information, just like interacting with local data. This greatly improves the smoothness of the application and prevents users from noticing the lag caused by data transmission.
const {
// Responsive states
data,
loading,
error,
// Events
onSuccess,
onError,
onComplete,
onBeforePushQueue,
onPushedQueue,
onFallback,
// Actions
send: submit,
abort,
update
// ...
} = useSQRequest(() => alova.Get('/api/todo/add'), {
behavior: 'silent',
queue: 'queue-demo',
silentDefaultResponse: () => {
return {
id: '--'
};
}
});
See Seamless Data Interaction for details.
Cross-component request triggering middleware
Cross-component request triggering middleware can help you eliminate the limitations of component levels and quickly trigger any request actions in any component.
- ComponentA
- ComponentB
useRequest(alova.Get('/api/todo/list'), {
// ...
middleware: actionDelegationMiddleware('action:todoList')
});
accessAction('action:todoList', delegatedActions => {
delegatedActions.send();
delegatedActions.abort();
});
See Cross-component request trigger for details.
Captcha strategy
Quickly implement captcha sending.
const mobile = ref('');
const {
// Responsive states
loading: sending,
countdown,
error,
// Events
onSuccess,
onError,
onComplete,
// Actions
send,
abort,
update
// ...
} = useCaptcha(
() =>
alova.Post('/api/captcha', {
mobile: mobile
}),
{
initialCountdown: 60
}
);
See Verification code strategy for details.
alova provides total 15+ client request strategies based on the RSM specification. Please refer Request Strategy List to see all client request strategies.
Server Request Strategy
On the server-side, such as in nodejs/deno/bun
, alova also provides server-side request strategies, which we call server hooks, all of which support cluster mode.
Below are introductions and examples of some server-side request strategies. Feel free to explore the ones that catch your interest.
Request Retry strategy
Retry the request if it fails.
const response = await retry(alova.Get('/api/user'), {
retry: 5
});
See Request retry strategy for details.
Request Rate Limit Strategy
Limit the number of requests within a certain period of time, support cluster mode.
const limit = createRateLimiter({
points: 4,
duration: 60 * 1000
});
const orderRes = await limit(alova.Get('/api/order'));
See Request Rate Limit Strategy for details.
More modern openAPI solution
- alova's devtools can simultaneously generate API call code, TypeScript types for each API, and comprehensive API documentation, allowing you to enjoy full API type hints even in JavaScript projects.
- In the past, when backend developers delivered APIs, you had to open the intermediate API documentation, search for and copy key information into your project, constantly switching between the API docs and your editor. Now, Alova's development tools can eliminate this intermediary documentation, bridging the frontend and backend collaboration like a wormhole. Through this tool, you can quickly find the APIs you need directly in your editor, display the API's complete documentation, and rapidly complete parameter passing by referencing the API parameter table - offering you an entirely new API integration experience.
For a detailed introduction to alova devtools, please refer to Integrated Editor Extension.
Building Client-Server Interaction Layer
With the various features of alova, you can also build a Client-Server interaction layer(CSIL) for your project. The CSIL will distribute response data to various components by merging same requests. Additionally, the CSIL also manages response data and the responsive states created by useHooks. You can access and modify the datas in CSIL in any UI component, as well as refresh the data in CSIL.
To learn how to build a CS Interaction Layer, refer to Building the Client-Server Interaction Layer
Run in any JS environment
alova is very flexible, you can use it with various request tools across any JavaScript environment (grayed-out options will be gradually supported in the future).
Migration Guide
Join alova community
Welcome to contribute
Before contributing, please be sure to read the Contribution Guide in detail to ensure your effective contribution.
Let's get started
Next, we will start with the simplest request, then explain the request strategy, understand how alova simplifies your work, and then go into the advanced guide and the best practices summarized in actual projects.
Let’s start learning alova!