Skip to content
Latestv1.0.63

useRequest

useRequest is a general-purpose request Hook provided by @yh-ui/request for elegantly managing the entire lifecycle of async requests in Vue components: loading state, errors, retry, debounce/throttle, etc.

Basic Usage

useRequest Basic Usage

Return Values

typescript
const {
  data, // ShallowRef<TData | undefined>
  loading, // Ref<boolean>
  error, // ShallowRef<RequestError | undefined>
  params, // Ref<TParams>
  loadingMore, // Ref<boolean> (works with pagination/load more)
  noMore, // Ref<boolean>
  run, // (...params: TParams) => Promise<RequestResponse<TData>>
  mutate, // (updater?: TData | ((old?: TData) => TData)) => void
  cancel, // () => void
  refresh, // () => Promise<void>
  loadMore, // () => Promise<void>
  disabled // ComputedRef<boolean>
} = useRequest(service, options)

Full Options

The options of useRequest(service, options) extend the request library's RequestOptions (e.g. baseURL, timeout..) and include these Hook-specific options:

OptionTypeDefaultDescription
manualbooleanfalseWhen true, request runs only after calling run()
defaultParamsTParams[]Default request params; used for the first request when not manual
debounceWaitnumber-Debounce time (ms) for multiple run calls
throttleWaitnumber-Throttle time (ms) for multiple run calls
requestRequest-Custom request instance
formatResult(response) => TData-Format response and extract business data from RequestResponse
onSuccess(data, params) => void-Success callback
onError(error, params) => void-Error callback
onFinally(params) => void-Finally callback (runs on success or failure)

Debounce & Throttle

Debounce & Throttle Demo

mutate: Local Data Update & cancel: Cancel Request

Optimistic Update & Request Cancellation

Polling (useRequestPolling)

Polling Demo

Polling options

OptionTypeDefaultDescription
pollingbooleanfalseEnable polling
pollingIntervalnumber3000Polling interval (ms)
pollingWhenHiddenbooleanfalsePause polling when page is not visible

Other options are the same as useRequest. Return value is the same as useRequest plus pause and resume.

Combine with SWR / Pagination

For more advanced usage, see:

Released under the MIT License.