useRequest — Request State
17:43Description
useRequest keeps the three page-request states (loading / data / error) and the lifecycle together: calling run() again cancels the previous pending request, stale responses are dropped by sequence number, and the request is canceled when the component unmounts.
When to use
useRequest targets a request block in a page that may run repeatedly, can be interrupted, and needs three states:
| Scenario | Why it fits | Key usage |
|---|---|---|
| Detail page loads on entry | The three states drive skeleton, empty and retry UI directly | { immediate: true } |
| Search / filter / paging | A new run cancels the pending one, so stale results never overwrite new ones | Call run() when conditions change |
| Dialog / drawer loads on open | Request only when opened, cancel on close | run() on open, cancel() on close |
| List pages behind tabs / routes | Unmount cancels automatically, no state writes after leaving | No extra code |
The snippets below reuse the api instance from Examples.
Load on page entry
ts
const detail = useRequest<JsonObject>((ctx) => {
return api.get('/get', null, { signal: ctx.signal } as HttpCallConfig).then((res: any) => {
return (res as HttpResponse).data as JsonObject;
});
}, { immediate: true });Refetch when conditions change
ts
const keyword = ref<string>('');
const list = useRequest<JsonObject>((ctx) => {
return api.get('/get?q=' + keyword.value, null, { signal: ctx.signal } as HttpCallConfig).then((res: any) => {
return (res as HttpResponse).data as JsonObject;
});
});
/** Call after the keyword / page changes: the pending request is canceled and stale responses are dropped */
const reload = (): void => {
list.run();
};Fetch on dialog open, cancel on close
ts
const detail = useRequest<JsonObject>((ctx) => {
return api.get('/get', null, { signal: ctx.signal } as HttpCallConfig).then((res: any) => {
return (res as HttpResponse).data as JsonObject;
});
});
const open = (): void => {
detail.run();
};
const close = (): void => {
detail.cancel(); // no need to wait for unmount
};When not to use
- Aggregating several endpoints: create one
useRequestper endpoint when each has its own three states; usePromise.alland manage state yourself when you need a single merged result. - Write operations such as form submits: a single loading flag with explicit success / failure branches is clearer with plain
await; the "drop stale responses" semantics means nothing for a submit. - Upload / download progress: progress comes from
UploadTask/DownloadTaskonProgressUpdate;useRequestonly covers Promise-based states. - Cross-page shared data:
useRequestdoes not cache or share; put shared data in a state layer.
Examples
useRequest
The fetcher receives ctx.signal; forward it to the http request to gain cancel support. run() resolves with Promise<void> and already stores failures in error, so no extra catch is needed.
View source
vue
<template>
<ux-button text="Request via useRequest" type="primary" shape="round" @click="run" />
<demo-result :text="summary" />
</template>
<script setup lang="ts">
import { http, useRequest } from '@/uni_modules/uview-pro-x';
import type { HttpCallConfig, HttpResponse } from '@/uni_modules/uview-pro-x';
const api = http.create({ baseURL: 'https://httpbin.org' });
const detail = useRequest<JsonObject>((ctx) => {
return api.get('/uuid', null, { signal: ctx.signal } as HttpCallConfig).then((res: any) => {
return (res as HttpResponse).data as JsonObject;
});
});
const summary = computed<string>(() => {
if (detail.loading.value) return 'Loading…';
const err = detail.error.value;
if (err != null) return err.message;
const data = detail.data.value;
if (data == null) return 'Not started';
return data['uuid'] as string;
});
const run = (): void => {
detail.run();
};
</script>API
Parameters
| Parameter | Description | Type | Default | Version |
|---|---|---|---|---|
| fetcher | Request function; forward ctx.signal to the request | (ctx: UseRequestContext) => Promise<T> | - | - |
| options | Options, may be omitted | UseRequestOptions | null | null | - |
| options.immediate | Whether to run once on setup | boolean | false | - |
Returns
| Field | Description | Type | Version |
|---|---|---|---|
| loading | Whether a request is in flight | Ref<boolean> | - |
| data | Resolved data, stored in a shallowRef | ShallowRef<T | null> | - |
| error | Failure error; cancels are not counted | Ref<HttpError | null> | - |
| run | Runs manually and cancels the previous pending request | () => Promise<void> | - |
| cancel | Cancels the current request and drops its result | () => void | - |
Notes
immediatedefaults tofalse; pass{ immediate: true }or callrun()inonMountedto request on entry.run()handles exceptions internally and writes them intoerror, so the returned Promise needs nocatch.- Canceling works only when the fetcher forwards
ctx.signal; otherwisecancel()just drops the result while the request continues. - Repeated
run()calls drop stale responses by sequence number, so old data never overwrites new data;loadingresets when the latest request settles. datais ashallowRef: only whole-value replacement triggers updates, mutating its fields in place does not refresh the view.- Cancels never write into
error; test them withhttp.isCancel.