Skip to content

useRequest — Request State ​

17:43

Description ​

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:

ScenarioWhy it fitsKey usage
Detail page loads on entryThe three states drive skeleton, empty and retry UI directly{ immediate: true }
Search / filter / pagingA new run cancels the pending one, so stale results never overwrite new onesCall run() when conditions change
Dialog / drawer loads on openRequest only when opened, cancel on closerun() on open, cancel() on close
List pages behind tabs / routesUnmount cancels automatically, no state writes after leavingNo 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 useRequest per endpoint when each has its own three states; use Promise.all and 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 / DownloadTask onProgressUpdate; useRequest only covers Promise-based states.
  • Cross-page shared data: useRequest does 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 ​

ParameterDescriptionTypeDefaultVersion
fetcherRequest function; forward ctx.signal to the request(ctx: UseRequestContext) => Promise<T>--
optionsOptions, may be omittedUseRequestOptions | nullnull-
options.immediateWhether to run once on setupbooleanfalse-

Returns ​

FieldDescriptionTypeVersion
loadingWhether a request is in flightRef<boolean>-
dataResolved data, stored in a shallowRefShallowRef<T | null>-
errorFailure error; cancels are not countedRef<HttpError | null>-
runRuns manually and cancels the previous pending request() => Promise<void>-
cancelCancels the current request and drops its result() => void-

Notes ​

  • immediate defaults to false; pass { immediate: true } or call run() in onMounted to request on entry.
  • run() handles exceptions internally and writes them into error, so the returned Promise needs no catch.
  • Canceling works only when the fetcher forwards ctx.signal; otherwise cancel() just drops the result while the request continues.
  • Repeated run() calls drop stale responses by sequence number, so old data never overwrites new data; loading resets when the latest request settles.
  • data is a shallowRef: only whole-value replacement triggers updates, mutating its fields in place does not refresh the view.
  • Cancels never write into error; test them with http.isCancel.