vue-use-api-call
v0.2.0
Published
A Vue 3 composable for making easy API calls with built-in loading state.
Maintainers
Readme
vue-use-api-call
Vue 3 composable for convenient handling of asynchronous operations. Makes it easy to manage loading state and error handling.
This library is inspired by TanStack Query but with a key difference: while TanStack Query focuses on data fetching and caching,
vue-use-api-callprovides a simpler way to handle any asynchronous operations and can be called not only in component setup but anywhere in your code.
Installation
npm install vue-use-api-call
# or
yarn add vue-use-api-call
# or
pnpm add vue-use-api-callUsage
Basic Example (destructuring)
<template>
<div>
<div v-if="isLoading">Loading...</div>
<button @click="call()" :disabled="isLoading">
{{ isLoading ? 'Loading...' : 'Do smth' }}
</button>
</div>
</template>
<script setup lang="ts">
import { useApiCall } from 'vue-use-api-call'
const { isLoading, call } = useApiCall({
cb: async () => {
// Your async operation
await fetch('https://api.example.com/do-smth')
}
})
// Execute the operation
call()
</script>
Basic Example (without destructuring)
<template>
<div>
<!-- You should use .value if you don't destructure composable -->
<div v-if="doSmth.isLoading.value">Loading...</div>
<button @click="doSmth.call()" :disabled="doSmth.isLoading.value">
{{ doSmth.isLoading.value ? 'Loading...' : 'Do smth' }}
</button>
</div>
</template>
<script setup lang="ts">
import { useApiCall } from 'vue-use-api-call'
const doSmth = useApiCall({
cb: async () => {
// Your async operation
await fetch('https://api.example.com/do-smth')
}
})
// Execute the operation
doSmth.call()
</script>
Fetching data
<template>
<div>
<div v-if="isLoading">Loading...</div>
<div>{{ data }}</div>
</div>
</template>
<script setup lang="ts">
import { useApiCall } from 'vue-use-api-call'
// Data will be auto typed depends on type of fetching result
const { isLoading, data } = useApiCall({
cb: async () => {
// Result of fetching will be stored in data variable
return await fetch('https://api.example.com/fetch-smth')
},
callOnInit: true, // Will be fetched automatically without call() method
})
</script>
Init as plugin (optional)
Plugin initialization is optional and is needed when you want to set up a global error handler that will be used when no catchCb is provided.
The plugin also registers useApiCall with app.provide('useApiCall', useApiCall), so you can inject it in nested components if needed (inject('useApiCall')).
// main.ts
import { createApp } from 'vue'
import App from './App.vue'
import useApiCallPlugin from 'vue-use-api-call'
const app = createApp(App)
// Initialize the plugin with default error handler
app.use(useApiCallPlugin, {
defaultErrorCb: (e) => {
// Global error handling logic (call toast for example)
toast('error', yourAmazingErrorHandler(e))
}
})
app.mount('#app')With Error Handling
<script setup lang="ts">
import { useApiCall } from 'vue-use-api-call'
const { isLoading, call } = useApiCall({
cb: async () => {
await fetch('https://api.example.com/do-smth')
},
catchCb: (e) => {
// Your error handling logic
}
})
</script>With Errors Variable
<script setup lang="ts">
import { useApiCall } from 'vue-use-api-call'
// Errors variable will be auto typed depends on type of catchCb returning value
const { isLoading, call, errors } = useApiCall({
cb: async () => {
await fetch('https://api.example.com/do-smth')
},
catchCb: (e) => {
// You can convert error to array or what you want
return yourAmazingErrorConverter(e)
}
})
</script>With Parameters
<script setup lang="ts">
import { useApiCall } from 'vue-use-api-call'
const { isLoading, call } = useApiCall({
cb: async (params: { userId: string }) => {
await fetch(`https://api.example.com/do-smth/${params.userId}`)
}
})
// Execute operation with parameters
call({ userId: '123' })
</script>API
Parameters
| Parameter | Type | Description |
|----------|-----|----------|
| cb | (args?: Args) => Promise<Data> \| Data | Main async function |
| defaultLoading | boolean | Initial loading state (default: false) |
| catchCb | (e: any) => Promise<Errors> \| Errors | Error handler |
| finallyCb | () => Promise<void> \| void | Callback called after operation completion |
| callOnInit | boolean | Whether to automatically execute the operation when the composable is initialized (default: false) |
Return Values
| Property | Type | Description |
|----------|-----|----------|
| call | (args?: Args, skipLoading = false) => Promise<void> | Function to execute the operation. The skipLoading parameter can be used to prevent showing loading state on subsequent calls, for example when you don't want to show loading screen on retry. |
| isLoading | Ref<boolean> | Loading flag |
| data | Ref<Data \| null> | Reactive reference to the data returned from the API call. The type Data is automatically inferred from the return type of the cb function. Stays null until the first successful completion of cb. |
| errors | Ref<Errors \| null> | Reactive reference to the error data returned from the catchCb function. The type Errors is automatically inferred from the return type of the catchCb function |
| reset | () => void | Resets data, errors, and isLoading to their initial values (data and errors to null, isLoading to defaultLoading) |
Behavior
While isLoading is true, further call() invocations are ignored if both defaultLoading and callOnInit are falsy (the default). Set defaultLoading: true or callOnInit: true if you need another call() to run while a request is already in flight.
Plugin Options
| Property | Type | Description |
|----------|-----|----------|
| defaultErrorCb | (e: any) => Promise<void> \| void | Global error handler that will be used when no catchCb is provided |
useApiCallWithPageAndSearch
Composable for fetching a paginated list with a search input. It auto-fetches on init, debounces search and aborts the previous in-flight request via AbortController. Request cancellation (AbortError) does not populate errors; those are cleared for aborted requests.
Usage
<script setup lang="ts">
import { useApiCallWithPageAndSearch } from 'vue-use-api-call'
type Data = {
list: { id: number; name: string }[]
pagination: { total: number; total_pages: number }
}
const { isLoading, data, page, changePage, search, onSearch, errors } =
useApiCallWithPageAndSearch({
cb: (query, signal) => getData(query, signal),
options: { defaultPerPage: 10 },
})
</script>
<template>
<div>
<div>
<input
:value="search"
placeholder="Search..."
@input="(e) => onSearch((e.target as HTMLInputElement).value)"
/>
</div>
<div style="display: flex; gap: 8px; align-items: center">
<button type="button" :disabled="isLoading || page <= 1" @click="changePage(page - 1)">
Prev
</button>
<div>Page: {{ page }}</div>
<button
type="button"
:disabled="isLoading || page >= (data?.pagination.total_pages ?? page)"
@click="changePage(page + 1)"
>
Next
</button>
</div>
<div v-if="isLoading">Loading...</div>
<div v-else-if="errors">{{ errors }}</div>
<div v-else-if="data?.list?.length">
<div v-for="item in data!.list" :key="item.id">
{{ item.name }}
</div>
</div>
<div v-else>No results</div>
</div>
</template>Parameters
useApiCallWithPageAndSearch<Data, Errors>({
cb: (
query: { page: number; perPage: number; search?: string },
signal: AbortSignal
) => Promise<Data>,
catchCb?: (e: any) => Promise<Errors> | Errors,
options?: {
defaultPage?: number // default: 1
defaultPerPage?: number // default: 20
debounceMs?: number // default: 800
mode?: 'route' | 'local' // default: 'route' (route: sync query via @vueuse/router; local: local refs)
pageQueryKey?: string // default: 'page'
perPageQueryKey?: string // default: 'per_page'
searchQueryKey?: string // default: 'search'
callOnInit?: boolean // default: true
}
})Return Values
| Property | Type | Description |
|----------|-----|----------|
| call | (args?: undefined, skipLoading?: boolean) => Promise<void> | Trigger fetch manually. skipLoading can be used to avoid showing loading state on subsequent calls |
| isLoading | Ref<boolean> | Loading flag |
| data | Ref<Data \| null> | Reactive reference to fetched data |
| errors | Ref<Errors \| null> | Reactive reference to converted error (from catchCb) |
| page | Ref<number> | Current page (route-synced in route mode) |
| changePage | (newPage: number, skipLoading?: boolean) => void | Set new page and fetch |
| search | Ref<string \| undefined> | Current search (route-synced in route mode) |
| onSearch | (newSearch?: string \| null) => void | Update search, reset page to 1, and fetch (debounced) |
License
MIT
