### Install VueRequest via NPM
Source: https://github.com/attojs/vue-request/blob/master/README.md
Install VueRequest using NPM, YARN, or PNPM. This is the recommended way to add the library to your project.
```sh
npm install vue-request
# or
yarn add vue-request
# or
pnpm install vue-request
```
--------------------------------
### Define a logging plugin for `useRequest`
Source: https://context7.com/attojs/vue-request/llms.txt
This plugin logs various lifecycle events of a `useRequest` instance. It requires no specific setup beyond being passed to `useRequest`.
```typescript
import { definePlugin, useRequest } from 'vue-request'
// Plugin that logs each request lifecycle event
const useLoggerPlugin = definePlugin((queryInstance, options) => {
return {
onBefore(params) {
console.log('[Request] Starting with params:', params)
},
onSuccess(data, params) {
console.log('[Request] Success:', data)
},
onError(error, params) {
console.error('[Request] Error after params', params, ':', error.message)
},
onAfter(params) {
console.log('[Request] Settled with params:', params)
},
onCancel() {
console.log('[Request] Cancelled')
},
}
})
```
--------------------------------
### `manual: true` Option for `useRequest`
Source: https://context7.com/attojs/vue-request/llms.txt
When `manual: true`, the request is not triggered on component mount. Use `run` or `runAsync` to trigger requests imperatively, useful for user-initiated actions.
```typescript
import { useRequest } from 'vue-request'
const { data, loading, run } = useRequest(fetchUser, { manual: true })
// Nothing has fired yet — trigger on user action:
function onButtonClick(id: number) {
run(id)
}
// Async variant with error handling:
async function submitForm(id: number) {
try {
const result = await runAsync(id)
console.log('Done', result)
} catch (e) {
console.error(e)
}
}
```
--------------------------------
### Basic VueRequest Usage
Source: https://github.com/attojs/vue-request/blob/master/README.md
Demonstrates the basic usage of VueRequest with the `useRequest` hook. It shows how to handle loading, error, and data states.
```vue
loading...
failed to fetch
Hey! {{ data }}
```
--------------------------------
### SWR-style Caching
Source: https://context7.com/attojs/vue-request/llms.txt
Implement SWR-style caching with options for cache key, cache duration, and stale time. Allows immediate stale data return while refreshing in the background.
```APIDOC
## `cacheKey` / `cacheTime` / `staleTime` options — SWR-style caching
Caches responses under a string key. On subsequent requests with the same key, stale data is returned immediately while a background refresh runs (`staleTime`). Set `staleTime: -1` to never revalidate from cache. Use `clearCache()` to invalidate programmatically.
```typescript
import { useRequest, clearCache } from 'vue-request'
const { data, loading } = useRequest(fetchUser, {
defaultParams: [1],
cacheKey: 'user-1', // static key
cacheTime: 300_000, // keep cache entry for 5 min (default 600 000 ms)
staleTime: 10_000, // serve from cache without re-fetching for 10 s
})
// Dynamic cache key based on params:
const { data: dynData } = useRequest(fetchUser, {
cacheKey: (params) => (params ? `user-${params[0]}` : ''),
staleTime: -1, // -1 = cache is always considered fresh
})
// Manually invalidate a single key:
clearCache('user-1')
// Wipe all cached entries:
clearCache()
```
```
--------------------------------
### useRequest - `manual` Option
Source: https://context7.com/attojs/vue-request/llms.txt
When `manual: true`, the request is not triggered on component mount. You control when it fires by calling `run` or `runAsync`.
```APIDOC
## `manual` Option
### Description
Prevents the `useRequest` composable from automatically triggering the service function on component mount. The request must be explicitly initiated by calling `run` or `runAsync`.
### Parameters
- `manual` (Boolean): If `true`, the request will not run automatically on mount.
### Example
```typescript
import { useRequest } from 'vue-request'
const { data, loading, run } = useRequest(fetchUser, {
manual: true
})
// Trigger the request manually, e.g., on a button click
function handleClick(id: number) {
run(id)
}
// Async variant with error handling
async function submitForm(id: number) {
try {
const result = await runAsync(id)
console.log('Form submitted successfully:', result)
} catch (e) {
console.error('Form submission failed:', e)
}
}
```
```
--------------------------------
### useRequest - `ready` Option
Source: https://context7.com/attojs/vue-request/llms.txt
Prevents the request from firing (auto or manual) until the provided ref or function returns `true`. When `ready` flips to `true`, an automatic re-run is triggered if `manual` is `false`.
```APIDOC
## `ready` Option
### Description
Acts as a gatekeeper for the request. The service function will only be executed if the `ready` condition evaluates to `true`. If `manual` is `false`, the request will automatically re-run when the `ready` condition becomes `true`.
### Parameters
- `ready` (Ref | Function): A Vue ref or a function that returns a boolean. The request is enabled only when this condition is met.
### Example
```typescript
import { ref } from 'vue'
import { useRequest } from 'vue-request'
const isLoggedIn = ref(false)
const { data, loading } = useRequest(fetchUser, {
defaultParams: [42],
ready: isLoggedIn, // The request will only run when isLoggedIn is true
})
// Simulate login
setTimeout(() => {
isLoggedIn.value = true // This will trigger the request if manual is false
}, 2000)
```
```
--------------------------------
### Wrap useRequest with useRequestProvider
Source: https://github.com/attojs/vue-request/blob/master/CHANGELOG.md
Users can now wrap the `useRequest` hook with `useRequestProvider` themselves to manage global configurations or state.
```javascript
import { useRequestProvider } from '@vue-request/core';
const app = createApp(App);
app.use(useRequestProvider(options));
app.mount('#app');
```
--------------------------------
### Basic `useRequest` Usage
Source: https://context7.com/attojs/vue-request/llms.txt
The primary `useRequest` composable wraps an async service function and returns reactive state and control methods. Configure behavior with options like `defaultParams`, `initialData`, and callbacks such as `onSuccess`, `onError`, `onBefore`, and `onAfter`.
```typescript
import { useRequest } from 'vue-request'
import axios from 'axios'
interface User { id: number; name: string }
const fetchUser = (id: number): Promise =>
axios.get(`/api/users/${id}`).then(r => r.data)
// Basic auto-run usage
const { data, loading, error, run, runAsync, refresh, cancel, mutate, params } =
useRequest(fetchUser, {
defaultParams: [1], // run with id=1 on mount
initialData: { id: 0, name: '' }, // value of data before first response
onSuccess(user, params) {
console.log('Fetched:', user.name, 'with params', params)
},
onError(err, params) {
console.error('Failed:', err.message)
},
onBefore(params) { console.log('Starting request with', params) },
onAfter(params) { console.log('Request finished with', params) },
})
// Manual trigger: run(id) fires the request imperatively
run(2)
// runAsync returns a Promise for await-based control flow
const user = await runAsync(3)
// Optimistic update without re-fetching
mutate({ id: 1, name: 'Updated locally' })
// or via updater function
mutate(old => ({ ...old!, name: 'Patched' }))
// Re-run with the same params that were last used
refresh()
// Cancel any in-flight request
cancel()
// Inspect the last params used
console.log(params.value) // [3]
```
--------------------------------
### Implement SWR-style Caching
Source: https://context7.com/attojs/vue-request/llms.txt
Cache responses using `cacheKey`. `staleTime` determines how long stale data is served, and `cacheTime` controls the entry's lifetime. Use `clearCache()` to invalidate entries.
```typescript
import { useRequest, clearCache } from 'vue-request'
const { data, loading } = useRequest(fetchUser, {
defaultParams: [1],
cacheKey: 'user-1', // static key
cacheTime: 300_000, // keep cache entry for 5 min (default 600 000 ms)
staleTime: 10_000, // serve from cache without re-fetching for 10 s
})
// Dynamic cache key based on params:
const { data: dynData } = useRequest(fetchUser, {
cacheKey: (params) => (params ? `user-${params[0]}` : ''),
staleTime: -1, // -1 = cache is always considered fresh
})
// Manually invalidate a single key:
clearCache('user-1')
// Wipe all cached entries:
clearCache()
```
--------------------------------
### Use custom plugins with `useRequest`
Source: https://context7.com/attojs/vue-request/llms.txt
Demonstrates how to pass custom plugins, such as `useLoggerPlugin` and `useAuthPlugin`, as the third argument to the `useRequest` hook.
```typescript
const { data } = useRequest(fetchUser, { defaultParams: [1] }, [
useLoggerPlugin,
useAuthPlugin,
])
```
--------------------------------
### Loading State Timing Control
Source: https://context7.com/attojs/vue-request/llms.txt
Control the timing of the loading state with `loadingDelay` to prevent spinner flicker on fast requests and `loadingKeep` to ensure the loading state is visible for a minimum duration.
```APIDOC
## `loadingDelay` / `loadingKeep` options — Loading state timing control
`loadingDelay` prevents the `loading` flag from flipping to `true` until the given number of milliseconds have elapsed, avoiding spinner flicker on fast requests. `loadingKeep` ensures the loading state is shown for at least the given duration, preventing jarring instant transitions.
```typescript
import { useRequest } from 'vue-request'
const { data, loading } = useRequest(fetchData, {
loadingDelay: 300, // only show spinner if request takes > 300 ms
loadingKeep: 1000, // keep spinner visible for at least 1 s after response
})
```
```
--------------------------------
### `ready` Option for Conditional Execution
Source: https://context7.com/attojs/vue-request/llms.txt
The `ready` option prevents requests from firing until a condition is met. When `ready` becomes true, an automatic re-run is triggered if `manual` is false. It accepts a ref or a function returning a boolean.
```typescript
import { ref } from 'vue'
import { useRequest } from 'vue-request'
const isLoggedIn = ref(false)
const { data } = useRequest(fetchUser, {
defaultParams: [42],
ready: isLoggedIn, // also accepts: ready: () => isLoggedIn.value
})
// No request fires while isLoggedIn.value === false
// Flipping it to true automatically fires the request:
setTimeout(() => { isLoggedIn.value = true }, 2000)
```
--------------------------------
### Provide Promise as Service in vue-request
Source: https://github.com/attojs/vue-request/blob/master/CHANGELOG.md
When using the `service` option, ensure it returns a Promise. Wrap your requests with libraries like axios.
```javascript
const getUser = userName => {
return axios.get('api/user', {
params: {
name: userName,
},
});
};
useRequest(getUser, options);
```
--------------------------------
### usePagination
Source: https://context7.com/attojs/vue-request/llms.txt
Extends useRequest with pagination state and helpers to navigate pages. The service receives pagination params automatically merged with any extra parameters.
```APIDOC
## `usePagination` — Paginated data fetching
Extends `useRequest` with pagination state (`current`, `pageSize`, `total`, `totalPage`) and helpers to navigate pages. The service receives pagination params automatically merged with any extra parameters.
```typescript
import { usePagination } from 'vue-request'
interface PageResult {
total: number
list: User[]
}
const fetchPage = ({ current, pageSize }: { current: number; pageSize: number }) =>
fetch(`/api/users?page=${current}&size=${pageSize}`).then(r => r.json()) as Promise
const {
data, loading, current, pageSize, total, totalPage,
changeCurrent, changePageSize, changePagination,
} = usePagination(fetchPage, {
defaultParams: [{ current: 1, pageSize: 20 }],
// Custom field names if your API uses different keys:
pagination: {
currentKey: 'page',
pageSizeKey: 'size',
totalKey: 'total',
totalPageKey: 'pages',
},
})
// Navigate:
changeCurrent(3) // go to page 3
changePageSize(50) // change to 50 items/page
changePagination(2, 10) // go to page 2 with 10 items/page
// current and pageSize are writable computed refs:
current.value = 4 // same as changeCurrent(4)
```
```
--------------------------------
### useRequest - Core Composable
Source: https://context7.com/attojs/vue-request/llms.txt
The primary composable `useRequest` wraps any async service function and returns reactive state plus control methods. It accepts optional `options` to configure built-in plugin behaviors and an optional `plugins` array for custom plugins.
```APIDOC
## useRequest
### Description
Wraps an async service function and returns reactive state (`data`, `loading`, `error`) along with control methods (`run`, `runAsync`, `refresh`, `cancel`, `mutate`, `params`). It can be configured with various options to manage request behavior.
### Parameters
- `service` (Function): The async function (Promise-returning) to be called.
- `options` (Object, optional): Configuration options for the request.
- `defaultParams` (Array, optional): Default parameters to pass to the service function on mount.
- `initialData` (any, optional): The initial value of `data` before the first successful request.
- `onSuccess` (Function, optional): Callback executed on successful request.
- `onError` (Function, optional): Callback executed on request error.
- `onBefore` (Function, optional): Callback executed before a request is made.
- `onAfter` (Function, optional): Callback executed after a request finishes (success or error).
### Returns
An object containing:
- `data` (Ref): Reactive reference to the fetched data.
- `loading` (Ref): Reactive reference indicating if a request is in progress.
- `error` (Ref): Reactive reference to any error that occurred.
- `run` (Function): Imperatively trigger the request with provided arguments.
- `runAsync` (Function): Imperatively trigger the request and return a Promise.
- `refresh` (Function): Re-run the request with the last used parameters.
- `cancel` (Function): Cancel any in-flight request.
- `mutate` (Function): Optimistically update the `data` without re-fetching.
- `params` (Ref): Reactive reference to the last parameters used for the request.
### Example
```typescript
import { useRequest } from 'vue-request'
import axios from 'axios'
const fetchUser = (id: number): Promise =>
axios.get(`/api/users/${id}`).then(r => r.data)
const { data, loading, error, run, runAsync, refresh, cancel, mutate, params } =
useRequest(fetchUser, {
defaultParams: [1],
initialData: { id: 0, name: '' },
onSuccess(user, params) { console.log('Fetched:', user.name) },
onError(err, params) { console.error('Failed:', err.message) },
})
// Manual trigger
run(2)
// Async usage
const user = await runAsync(3)
// Optimistic update
mutate({ id: 1, name: 'Updated locally' })
// Re-run
refresh()
// Cancel request
cancel()
// Inspect params
console.log(params.value)
```
```
--------------------------------
### Use runAsync for Promise Return
Source: https://github.com/attojs/vue-request/blob/master/CHANGELOG.md
The `run` function no longer returns a Promise. Use `runAsync` if you need to handle the Promise returned by the service.
```javascript
// Original run function no longer returns a Promise
// useRequest(getUser, options).run();
// Use runAsync instead
// useRequest(getUser, options).runAsync();
```
--------------------------------
### Define an authentication plugin for `useRequest`
Source: https://context7.com/attojs/vue-request/llms.txt
This plugin injects an Authorization header by modifying the service call within the `onQuery` lifecycle. It retrieves the token from `localStorage`.
```typescript
// Plugin that injects an Authorization header by monkey-patching the service
const useAuthPlugin = definePlugin((queryInstance) => {
return {
onQuery(service) {
return async () => {
const token = localStorage.getItem('token')
// wrap service call — not shown: patching headers externally
return service()
}
},
}
})
```
--------------------------------
### useRequestProvider
Source: https://context7.com/attojs/vue-request/llms.txt
Inject global options into a component tree. Provides default options to all `useRequest`, `usePagination`, and `useLoadMore` calls within a component subtree, without setting process-wide globals.
```APIDOC
## `useRequestProvider` — Inject global options into a component tree
Provides default options to all `useRequest`, `usePagination`, and `useLoadMore` calls within a component subtree, without setting process-wide globals.
```typescript
// ParentComponent.vue
import { defineComponent } from 'vue'
import { useRequestProvider } from 'vue-request'
export default defineComponent({
setup() {
useRequestProvider({
errorRetryCount: 3,
loadingDelay: 200,
refreshOnWindowFocus: true,
pagination: { currentKey: 'page', pageSizeKey: 'limit' },
})
},
})
// ChildComponent.vue — inherits the provider's options automatically
import { useRequest } from 'vue-request'
const { data } = useRequest(fetchSomething) // uses errorRetryCount: 3, etc.
```
```
--------------------------------
### Reactivity in useRequest Options
Source: https://github.com/attojs/vue-request/blob/master/CHANGELOG.md
Illustrates how various options for useRequest can be made reactive using Vue's Ref or Reactive types. This allows for dynamic updates to request behavior.
```typescript
type ReactivityOptions = {
loadingDelay: number | Ref;
loadingKeep: number | Ref;
pollingInterval: number | Ref;
debounceInterval: number | Ref;
debounceOptions: DebounceOptions | Reactive;
throttleInterval: number | Ref;
throttleOptions: ThrottleOptions | Reactive;
refreshOnWindowFocus: boolean | Ref;
refocusTimespan: number | Ref;
errorRetryCount: number | Ref;
errorRetryInterval: number | Ref;
};
```
--------------------------------
### Custom Cache Key Function in useRequest
Source: https://github.com/attojs/vue-request/blob/master/CHANGELOG.md
Demonstrates how to define a custom cache key function for useRequest, which allows dynamic cache key generation based on request parameters. Handles undefined parameters during initialization.
```typescript
useRequest(getUser, {
cacheKey: (params?: P): string => {
// When initialized, `params` will be undefined, so we need to manually check and return an empty string
if (params) {
return `user-key-${params[0].name}`;
}
return '';
},
});
```
--------------------------------
### Include VueRequest via CDN
Source: https://github.com/attojs/vue-request/blob/master/README.md
Include VueRequest using a CDN link for direct use in HTML. For production, it's recommended to link to a specific version.
```html
```
--------------------------------
### useRequestProvider - Inject Global Options
Source: https://context7.com/attojs/vue-request/llms.txt
Provides default options to all useRequest, usePagination, and useLoadMore calls within a component subtree. This is useful for setting options like error retry counts or loading delays for specific parts of an application.
```typescript
// ParentComponent.vue
import { defineComponent } from 'vue'
import { useRequestProvider } from 'vue-request'
export default defineComponent({
setup() {
useRequestProvider({
errorRetryCount: 3,
loadingDelay: 200,
refreshOnWindowFocus: true,
pagination: { currentKey: 'page', pageSizeKey: 'limit' },
})
},
})
// ChildComponent.vue — inherits the provider's options automatically
import { useRequest } from 'vue-request'
const { data } = useRequest(fetchSomething) // uses errorRetryCount: 3, etc.
```
--------------------------------
### usePagination - Paginated Data Fetching
Source: https://context7.com/attojs/vue-request/llms.txt
Extends useRequest with pagination state and helpers. The service receives pagination params automatically merged with extra parameters. Use defaultParams to set initial pagination values.
```typescript
import { usePagination } from 'vue-request'
interface PageResult {
total: number
list: User[]
}
const fetchPage = ({ current, pageSize }: { current: number; pageSize: number }) =>
fetch(`/api/users?page=${current}&size=${pageSize}`).then(r => r.json()) as Promise
const {
data, loading, current, pageSize, total, totalPage,
changeCurrent, changePageSize, changePagination,
} = usePagination(fetchPage, {
defaultParams: [{ current: 1, pageSize: 20 }],
// Custom field names if your API uses different keys:
pagination: {
currentKey: 'page',
pageSizeKey: 'size',
totalKey: 'total',
totalPageKey: 'pages',
},
})
// Navigate:
changeCurrent(3) // go to page 3
changePageSize(50) // change to 50 items/page
changePagination(2, 10) // go to page 2 with 10 items/page
// current and pageSize are writable computed refs:
current.value = 4 // same as changeCurrent(4)
```
--------------------------------
### Watch Reactive Dependencies for Re-fetching
Source: https://context7.com/attojs/vue-request/llms.txt
Use `refreshDeps` to re-run requests when specified refs or reactive sources change. `refreshDepsAction` allows customization of the re-run behavior.
```typescript
import { ref } from 'vue'
import { useRequest } from 'vue-request'
const userId = ref(1)
const role = ref('admin')
const { data } = useRequest(fetchUser, {
refreshDeps: [userId, role],
// custom action instead of default refresh():
refreshDepsAction() {
run(userId.value)
},
})
// Changing either ref automatically re-fetches:
userId.value = 2
```
--------------------------------
### setGlobalOptions - Set Process-Wide Defaults
Source: https://context7.com/attojs/vue-request/llms.txt
Sets default options for every useRequest, usePagination, and useLoadMore call across the entire application. Typically called once in main.ts/main.js. This affects all requests globally.
```typescript
import { createApp } from 'vue'
import { setGlobalOptions } from 'vue-request'
import App from './App.vue'
setGlobalOptions({
errorRetryCount: 2,
loadingDelay: 300,
cacheTime: 60_000,
staleTime: 5_000,
refreshOnWindowFocus: false,
pagination: {
currentKey: 'page',
pageSizeKey: 'per_page',
totalKey: 'total_count',
},
})
createApp(App).mount('#app')
```
--------------------------------
### Reactive Dependency Watching
Source: https://context7.com/attojs/vue-request/llms.txt
Re-run requests automatically when specified reactive dependencies change. Allows for custom actions upon dependency change.
```APIDOC
## `refreshDeps` / `refreshDepsAction` options — Reactive dependency watching
Re-runs the request whenever any of the watched refs/reactive sources change. Provide `refreshDepsAction` to override the default re-run behavior.
```typescript
import { ref } from 'vue'
import { useRequest } from 'vue-request'
const userId = ref(1)
const role = ref('admin')
const { data } = useRequest(fetchUser, {
refreshDeps: [userId, role],
// custom action instead of default refresh():
refreshDepsAction() {
run(userId.value)
},
})
// Changing either ref automatically re-fetches:
userId.value = 2
```
```
--------------------------------
### Control Loading State Timing
Source: https://context7.com/attojs/vue-request/llms.txt
Use `loadingDelay` to postpone the `loading` flag becoming true for fast requests, preventing spinner flicker. `loadingKeep` ensures the loading state persists for a minimum duration after a response.
```typescript
import { useRequest } from 'vue-request'
const { data, loading } = useRequest(fetchData, {
loadingDelay: 300, // only show spinner if request takes > 300 ms
loadingKeep: 1000, // keep spinner visible for at least 1 s after response
})
```
--------------------------------
### setGlobalOptions
Source: https://context7.com/attojs/vue-request/llms.txt
Set process-wide default options. Sets default options for every `useRequest`, `usePagination`, and `useLoadMore` call across the entire application. Typically called once in `main.ts`/`main.js`.
```APIDOC
## `setGlobalOptions` — Set process-wide default options
Sets default options for every `useRequest`, `usePagination`, and `useLoadMore` call across the entire application. Typically called once in `main.ts`/`main.js`.
```typescript
import { createApp } from 'vue'
import { setGlobalOptions } from 'vue-request'
import App from './App.vue'
setGlobalOptions({
errorRetryCount: 2,
loadingDelay: 300,
cacheTime: 60_000,
staleTime: 5_000,
refreshOnWindowFocus: false,
pagination: {
currentKey: 'page',
pageSizeKey: 'per_page',
totalKey: 'total_count',
},
})
createApp(App).mount('#app')
```
```
--------------------------------
### useLoadMore
Source: https://context7.com/attojs/vue-request/llms.txt
Accumulates results in a flat `dataList` computed ref across multiple calls to `loadMore`. Tracks `loadingMore` separately from the initial `loading` flag and exposes a `noMore` computed ref driven by the `isNoMore` callback.
```APIDOC
## `useLoadMore` — Infinite scroll / load-more
Accumulates results in a flat `dataList` computed ref across multiple calls to `loadMore`. Tracks `loadingMore` separately from the initial `loading` flag and exposes a `noMore` computed ref driven by the `isNoMore` callback.
```typescript
import { useLoadMore } from 'vue-request'
interface FeedPage { list: Post[]; nextCursor: string | null }
const fetchFeed = (lastPage?: FeedPage): Promise =>
fetch(`/api/feed?cursor=${lastPage?.nextCursor ?? ''}`).then(r => r.json())
const {
data, dataList, loading, loadingMore, noMore,
loadMore, loadMoreAsync, refresh, cancel, mutate,
} = useLoadMore(fetchFeed, {
isNoMore: (d) => d?.nextCursor === null,
onSuccess(page) { console.log('Total items loaded:', dataList.value.length) },
errorRetryCount: 2,
})
// Trigger next page:
function onScrollBottom() {
if (!noMore.value && !loadingMore.value) {
loadMore()
}
}
// Async variant:
async function onScrollBottomAsync() {
if (noMore.value) return
try {
await loadMoreAsync()
} catch (e) { /* handle */ }
}
// Reset to first page:
refresh()
```
```
--------------------------------
### Configure Refresh on Window Focus
Source: https://context7.com/attojs/vue-request/llms.txt
Automatically re-run requests when the user focuses the window or tab using `refreshOnWindowFocus`. `refocusTimespan` limits the frequency of these automatic refreshes.
```typescript
import { useRequest } from 'vue-request'
const { data } = useRequest(fetchUserProfile, {
refreshOnWindowFocus: true,
refocusTimespan: 5000, // at most once every 5 s (default)
})
```
--------------------------------
### Rate Limiting Requests
Source: https://context7.com/attojs/vue-request/llms.txt
Apply debounce or throttle intervals to `run`/`runAsync` calls for managing request frequency, suitable for search inputs or preventing request bursts.
```APIDOC
## `debounceInterval` / `throttleInterval` options — Rate limiting requests
Debounce or throttle calls to `run`/`runAsync`, useful for search-as-you-type or burst prevention. Both accept a reactive `Ref` so the interval can be changed at runtime.
```typescript
import { ref } from 'vue'
import { useRequest } from 'vue-request'
const searchQuery = ref('')
// Debounce: fires 500 ms after the last run() call
const { data: searchResults } = useRequest(
(q: string) => fetch(`/api/search?q=${q}`).then(r => r.json()),
{
manual: true,
debounceInterval: 500,
debounceOptions: { leading: false, trailing: true },
},
)
watch(searchQuery, q => run(q))
// Throttle: fires at most once per second
const { run: throttledSubmit } = useRequest(submitForm, {
manual: true,
throttleInterval: 1000,
throttleOptions: { leading: true, trailing: false },
})
```
```
--------------------------------
### Refresh on Window Focus
Source: https://context7.com/attojs/vue-request/llms.txt
Automatically re-run requests when the user focuses the browser tab. Includes an option to set a minimum interval between automatic refreshes.
```APIDOC
## `refreshOnWindowFocus` / `refocusTimespan` options — Refresh on tab focus
Re-runs the request when the user returns to the window/tab, with a minimum interval between automatic refreshes.
```typescript
import { useRequest } from 'vue-request'
const { data } = useRequest(fetchUserProfile, {
refreshOnWindowFocus: true,
refocusTimespan: 5000, // at most once every 5 s (default)
})
```
```
--------------------------------
### Implement Debounce and Throttle for Requests
Source: https://context7.com/attojs/vue-request/llms.txt
Control request frequency with `debounceInterval` or `throttleInterval`. `debounceInterval` delays execution until after a pause, while `throttleInterval` limits execution to once per interval. Intervals can be reactive.
```typescript
import { ref } from 'vue'
import { useRequest } from 'vue-request'
const searchQuery = ref('')
// Debounce: fires 500 ms after the last run() call
const { data: searchResults } = useRequest(
(q: string) => fetch(`/api/search?q=${q}`).then(r => r.json()),
{
manual: true,
debounceInterval: 500,
debounceOptions: { leading: false, trailing: true },
},
)
watch(searchQuery, q => run(q))
// Throttle: fires at most once per second
const { run: throttledSubmit } = useRequest(submitForm, {
manual: true,
throttleInterval: 1000,
throttleOptions: { leading: true, trailing: false },
})
```
--------------------------------
### Format Data within Service Function
Source: https://github.com/attojs/vue-request/blob/master/CHANGELOG.md
The `formatResult` option has been removed. Format your data directly within your `service` function.
```javascript
const getUser = async () => {
const results = await axios.get('api/user');
// Format the final data here
return results.data;
};
```
--------------------------------
### Automatic Refresh on Window Focus
Source: https://github.com/attojs/vue-request/blob/master/README.md
Configure VueRequest to automatically re-fetch data when the browser window regains focus. Useful for keeping data consistent across multiple windows or after system sleep.
```typescript
const { data, error, run } = useRequest(getUserInfo, {
refreshOnWindowFocus: true,
refocusTimespan: 1000, // 请求间隔时间
});
```
--------------------------------
### Refresh Data on Window Focus
Source: https://github.com/attojs/vue-request/blob/master/README-en_US.md
Use `refreshOnWindowFocus` to automatically re-fetch data when the user returns to the tab or window. Set `refocusTimespan` to control the minimum interval between refreshes.
```typescript
const { data, error, run } = useRequest(getUserInfo, {
refreshOnWindowFocus: true,
refocusTimespan: 1000, // refresh interval 1s
});
```
--------------------------------
### useRequest - `pollingInterval` Option
Source: https://context7.com/attojs/vue-request/llms.txt
Re-runs the service at a fixed interval in milliseconds. The polling can be configured to pause when the tab is hidden or the network is offline, and resumes automatically.
```APIDOC
## `pollingInterval` Option
### Description
Enables periodic re-execution of the service function at a specified interval. The polling behavior can be controlled regarding visibility and network status.
### Parameters
- `pollingInterval` (Number | Ref): The interval in milliseconds at which to re-run the service. Can be a reactive ref.
- `pollingWhenHidden` (Boolean, optional): If `false`, polling pauses when the document is hidden (e.g., tab is inactive). Defaults to `false`.
- `pollingWhenOffline` (Boolean, optional): If `false`, polling pauses when the network connection is lost. Defaults to `false`.
### Example
```typescript
import { ref } from 'vue'
import { useRequest } from 'vue-request'
const interval = ref(3000) // Poll every 3 seconds
const { data, cancel } = useRequest(fetchLatestPrices, {
pollingInterval: interval,
pollingWhenHidden: false, // Pause when tab is hidden
pollingWhenOffline: false, // Pause when offline
})
// Dynamically change the polling interval
setTimeout(() => { interval.value = 10000 }, 60000) // Change to 10 seconds after 1 minute
// Stop polling
function stopPolling() {
cancel()
}
```
```
--------------------------------
### useLoadMore - Infinite Scroll / Load-More
Source: https://context7.com/attojs/vue-request/llms.txt
Accumulates results in a flat dataList across multiple calls to loadMore. Tracks loadingMore separately from the initial loading flag and exposes a noMore computed ref driven by the isNoMore callback. Use isNoMore to define the condition for when there are no more items to load.
```typescript
import { useLoadMore } from 'vue-request'
interface FeedPage { list: Post[]; nextCursor: string | null }
const fetchFeed = (lastPage?: FeedPage): Promise =>
fetch(`/api/feed?cursor=${lastPage?.nextCursor ?? ''}`).then(r => r.json())
const {
data, dataList, loading, loadingMore, noMore,
loadMore, loadMoreAsync, refresh, cancel, mutate,
} = useLoadMore(fetchFeed, {
isNoMore: (d) => d?.nextCursor === null,
onSuccess(page) { console.log('Total items loaded:', dataList.value.length) },
errorRetryCount: 2,
})
// Trigger next page:
function onScrollBottom() {
if (!noMore.value && !loadingMore.value) {
loadMore()
}
}
// Async variant:
async function onScrollBottomAsync() {
if (noMore.value) return
try {
await loadMoreAsync()
} catch (e) { /* handle */ }
}
// Reset to first page:
refresh()
```
--------------------------------
### Automatic Error Retry
Source: https://context7.com/attojs/vue-request/llms.txt
Configure automatic retries for failed requests with options for retry count and interval. Supports exponential backoff by default.
```APIDOC
## `errorRetryCount` / `errorRetryInterval` options — Automatic error retry
Re-fires the request after a failure. Uses exponential backoff by default when `errorRetryInterval` is not specified. Set `errorRetryCount: -1` for infinite retries.
```typescript
import { useRequest } from 'vue-request'
const { data, error, loading } = useRequest(fetchUser, {
defaultParams: [1],
errorRetryCount: 3, // retry up to 3 times (-1 = infinite)
errorRetryInterval: 2000, // wait 2 s between retries (omit for exponential backoff)
onError(err) {
console.warn('Request failed, will retry:', err.message)
},
onSuccess(data) {
console.log('Succeeded after retries:', data)
},
})
```
```
--------------------------------
### clearCache - Programmatic Cache Invalidation
Source: https://context7.com/attojs/vue-request/llms.txt
Removes one or all entries from the in-memory SWR cache. Call without arguments to wipe all cached data, or pass a specific cacheKey string to invalidate just that entry. Useful after mutations to ensure fresh data is fetched.
```typescript
import { useRequest, clearCache } from 'vue-request'
useRequest(fetchUser, { defaultParams: [1], cacheKey: 'user-1' })
useRequest(fetchPosts, { cacheKey: 'posts' })
// Invalidate a single entry (e.g., after a mutation):
async function deleteUser(id: number) {
await api.delete(`/users/${id}`)
clearCache('user-1')
}
// Invalidate everything (e.g., on logout):
function logout() {
clearCache()
}
```
--------------------------------
### Configure Automatic Error Retries
Source: https://context7.com/attojs/vue-request/llms.txt
Set `errorRetryCount` to specify the number of retries. Use `errorRetryInterval` for a fixed delay between retries, or omit it for exponential backoff. Set `errorRetryCount` to -1 for infinite retries.
```typescript
import { useRequest } from 'vue-request'
const { data, error, loading } = useRequest(fetchUser, {
defaultParams: [1],
errorRetryCount: 3, // retry up to 3 times (-1 = infinite)
errorRetryInterval: 2000, // wait 2 s between retries (omit for exponential backoff)
onError(err) {
console.warn('Request failed, will retry:', err.message)
},
onSuccess(data) {
console.log('Succeeded after retries:', data)
},
})
```
--------------------------------
### Polling for Data Updates
Source: https://github.com/attojs/vue-request/blob/master/README.md
Enable periodic data re-fetching using `pollingInterval`. This ensures data consistency across devices by regularly updating the displayed information.
```typescript
const { data, error, run } = useRequest(getUserInfo, {
pollingInterval: 1000, // 请求间隔时间
});
```
--------------------------------
### clearCache
Source: https://context7.com/attojs/vue-request/llms.txt
Programmatic cache invalidation. Removes one or all entries from the in-memory SWR cache. Call without arguments to wipe all cached data, or pass a specific `cacheKey` string to invalidate just that entry.
```APIDOC
## `clearCache` — Programmatic cache invalidation
Removes one or all entries from the in-memory SWR cache. Call without arguments to wipe all cached data, or pass a specific `cacheKey` string to invalidate just that entry.
```typescript
import { useRequest, clearCache } from 'vue-request'
useRequest(fetchUser, { defaultParams: [1], cacheKey: 'user-1' })
useRequest(fetchPosts, { cacheKey: 'posts' })
// Invalidate a single entry (e.g., after a mutation):
async function deleteUser(id: number) {
await api.delete(`/users/${id}`)
clearCache('user-1')
}
// Invalidate everything (e.g., on logout):
function logout() {
clearCache()
}
```
```
--------------------------------
### `pollingInterval` Option for Interval Polling
Source: https://context7.com/attojs/vue-request/llms.txt
Re-run the service at a fixed interval specified in milliseconds. Polling pauses automatically when the tab is hidden or the network is offline, and resumes on visibility or reconnect. The interval can be a reactive ref.
```typescript
import { ref } from 'vue'
import { useRequest } from 'vue-request'
const interval = ref(3000)
const { data, cancel } = useRequest(fetchLatestPrices, {
pollingInterval: interval, // reactive — change interval.value at runtime
pollingWhenHidden: false, // pause when tab is hidden (default)
pollingWhenOffline: false, // pause when offline (default)
})
// Dynamically slow down polling:
interval.value = 10_000
// Stop polling entirely:
cancel()
```
--------------------------------
### Poll Data Periodically
Source: https://github.com/attojs/vue-request/blob/master/README-en_US.md
Utilize `pollingInterval` to periodically re-request data, ensuring synchronization across devices or real-time updates. This is useful when data changes frequently and needs to be reflected across multiple views.
```typescript
const { data, error, run } = useRequest(getUserInfo, {
pollingInterval: 1000, // polling interval 1s
});
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.