Public API

VueRequest usually consists of three parts: Return Values, Service, and Options

const { ...ReturnValues } = useRequest<R, P, FR>(Service, Options);

TS Generic description

R is a generic type of data.

P is a generic of params. (Note: This generic is subject to unknown[] constraints)

FR is the type of data returned by formatResult. (Note: The R generics mentioned in the following documents, after using formatResult, use FR instead)

Return Values

data

  • Type: Ref<R | undefined>

  • Default: undefined

    The data returned by request, if formatResult is passed in, the data returned by request will be the formatted data.

loading

  • Type: Ref<boolean>

  • Default: false

    Service The execution status of the request

reloading New in 1.2.0

  • Type: Ref<boolean>

  • Default: false

    Is reloading, used to record whether reload() is triggering.

params

  • Type: Ref<P[]>

  • Default: []

    Service request parameters

  • Usage:

function getUser(name) {
  return fetch('api/user?' + new URLSearchParams({ name })).then(res => res.json());
}

const { params, run } = useRequest(getUser, {
  defaultParams: ['John'],
});
// In the default request, if defaultParams exists, params. the value will be equal to defaultParams. Otherwise, it will be an empty array.

// When run passes in parameters, the parameters at this time will be synchronized to params
run('Benny'); // params.value is ['Benny']

error

  • Type: Ref<Error | undefined>

  • Default: undefined

    If an error is thrown internally, it will be received by error and returned.

queries

  • Type: Queries<R, P>

  • Default: Object

    By default, the newly requested data will overwrite the old requested data. When queryKey() is enabled, queries can store the results of multiple requests at the same time, achieving parallel effects

    Note

    queries is a reactiveopen in new window object

    The types of Queries are as follows.

    type Queries<R, P> = {
      loading: boolean;
      data: R | undefined;
      error: Error | undefined;
      params: P[];
      run: (...params: P[]) => Promise<R>;
      cancel: () => void;
      refresh: () => Promise<R>;
      mutate: (arg: (oldData: R) => R) => void | (newData: R) => void;
    }
    
  • See also: Concurrent Request

run

cancel

  • Type: () => void

    • Manually cancel the current request.
    • Pause polling.

    Note

    The cancellation mentioned here is not a real stop request but cancels the assignment of data and resets loading to false. The current request will not be interrupted.

refresh

  • Type: () => Promise<R>

    Recall run with the current params.

reload

mutate

  • Type: (arg: (oldData: R) => R) => void | (newData: R) => void

    Modify data directly

  • See also: Mutation

Service

For the request. See also Data Fetching

Request Method

  • Type:

    • (...params: P[]) => Promise<R>
    • | (...params: P[]) => string
    • | (...params: P[]) => ({ url: string; [key: string]: any; })
  • Details:

    You can pass in a function whose return value is Promise, String or Object. We recommend returning a Promise directly. You can use third-party request library (such as axios) to help you generate a Promise function for initiating a request to obtain resources.

    import { useRequest } from 'vue-request';
    import axios from 'axios';
    
    const getUser = () => {
      return axios.get('api/user');
    };
    
    const { data } = useRequest(getUser);
    

String

  • Type: string

  • Details:

    If you pass in a string or call it by returning a string from Request Method, then we will use the global fetch()open in new window method to initiate a request to obtain resources, this string will be used as the URL for obtaining resources

Object

  • Type: { url: string; [key: string]: any; }

  • Details:

    If you pass in an object or call it by returning an object via Request Method, then we will use the global fetch()open in new window method to initiate a request for resources. The object must contain a key-value pair named URL, which will be used as the URL for obtaining resources.

Options

loadingDelay

  • Type: number

  • Default: 0

  • Details:

    By setting the delay in milliseconds, you can delay the time loading becomes true, effectively preventing flicker.

  • See also: Loading Delay

pollingInterval

  • Type: number

  • Default: undefined

  • Details:

    By setting the polling interval's millisecond value, you can enter the polling mode and trigger the request regularly. You can use run / cancel to enable/stop polling. When manual is set to true, you need to execute a run before starting polling manually.

    • The interval value must be greater than 0 to take effect
  • See also: Polling

pollingWhenHidden

  • Type: boolean

  • Default: false

  • Details:

    It takes effect when pollingInterval is greater than 0. By default, polling will be suspended when the screen is not visible. When set to true, polling tasks will still be executed regularly when the screen is not visible.

  • See also: PollingWhenHidden

pollingWhenOffline

  • Type: boolean

  • Default: false

  • Details:

    It takes effect when pollingInterval is greater than 0. By default, polling will be suspended when the network is unavailable. When set to true, the polling task will still be executed regularly when the network is not available.

  • See also: PollingWhenOffline

debounceInterval

  • Type: number

  • Default: undefined

  • Details:

    Enter the debounce mode by setting the number of milliseconds to delay. At this time, if run is triggered frequently, the request will be made with the debounce strategy.

  • See also: Debounce

debounceOptions New in 1.2.2

  • Type: Object
  • Default:
{
  leading: false,
  maxWait: undefined,
  trailing: true
}
  • Details:

    • leading (boolean): Specify invoking on the leading edge of the timeout.
    • maxWait (number): The maximum time request function is allowed to be delayed before it's invoked.
    • trailing (boolean): Specify invoking on the trailing edge of the timeout.

throttleInterval

  • Type: number

  • Default: undefined

  • Details:

    Enter the throttling mode by setting the number of milliseconds for throttling. At this time, if run is triggered frequently, the request will be made with a throttling strategy.

  • See also: Throttle

throttleOptions New in 1.2.2

  • Type: Object
  • Default:
{
  leading: true,
  trailing: true,
}
  • Details:

    • leading (boolean): Specify invoking on the leading edge of the timeout.
    • trailing (boolean): Specify invoking on the trailing edge of the timeout.

refreshOnWindowFocus

refocusTimespan

  • Type: number

  • Default: 5000

  • Details:

    When refreshOnWindowFocus is set to true, you can limit the execution interval of refresh by setting the interval in milliseconds. The default is 5000ms.

  • See also: RefocusTimespan

cacheKey

  • Type: string

  • Default: undefined

  • Details:

    • We will cache every request data, error, params, loading
    • If cacheKey is set, VueRequest will cache the current request data. When the next component is initialized, if there is cached data, we will return the cached data first and then send a new request behind the scenes. After the new data is returned, we will trigger the data update and update the cached data again, which is the ability of SWR.
    • The request for the same cacheKey is shared globally. i.e., you can load data in advance. With this feature, preloading can be easily achieved.
  • See also: Cache / Preload

cacheTime

  • Type: number

  • Default: 600000

  • Details:

    When the cache is turned on, you can tell us the cache's expiration time by setting cacheTime. When the cache expires, we will delete it. The default is 600000 milliseconds, which is 10 minutes.

  • See also: CacheTime

staleTime

  • Type: number

  • Default: 0

  • Details:

    If you can ensure that the cached data will not be updated in a certain period of time, we recommend that you set a reasonable number of milliseconds.

    • The default is 0, which means no preservation, and the request will be reissued every time.
    • Set to -1 means the cache will never expire.
  • See also: StaleTime

errorRetryCount

  • Type: number

  • Default: 0

  • Details:

    Max error retry count

  • See also: ErrorRetryCount

errorRetryInterval

manual

  • Type: boolean

  • Default: false

  • Details:

    When manual is set to true, you need to manually trigger run to initiate the request.

  • See also: Manually Trigger

defaultParams

  • Type: P[]

  • Default: []

  • Details:

    If manual is set to false, when the run is automatically executed, defaultParams will be used as the request parameter.

ready

  • Type: Ref<boolean>

  • Default: true

  • Details:

    Only when ready is true will the request be initiated.

    • This behavior is only triggered once. If you want to trigger multiple times, it is recommended to use refreshDeps or implement the relevant logic yourself.
  • See also: Dependent Request

initialData

  • Type: R

  • Default: undefined

  • Details:

    Initialized data.

refreshDeps

  • Type: WatchSource<any>[]

  • Default: []

  • Details:

    The change of refreshDeps will trigger the re-execution of refresh. Its essence is just an encapsulation of watchopen in new window

    watch(refreshDeps, refresh);
    
  • See also: Dependency Refresh

queryKey

  • Type: (...params: P[]) => string

  • Details:

    According to params, get the key of the current request. After setting, we will maintain the request status with different key values in queries at the same time.

  • See also: Concurrent Request

formatResult

  • Type: (data: R) => FR

  • Details:

    Format the request result, the input parameter is the data returned by the original interface, and the output parameter is the processed data.

    import { defineComponent } from 'vue';
    import { useRequest } from 'vue-request';
    
    export default defineComponent({
      name: 'App',
      setup() {
        const { data } = useRequest<number, any, string>('api/timestramp', {
          formatResult: data => {
            return new Date(data);
          },
        });
        return () => <div>{data.value}</div>;
      },
    });
    

onSuccess

  • Type: (data: R, params: P[]) => void

  • Details:

    Triggered when Service resolve, the parameters are data and params.

onError

  • Type: (error: Error, params: P[]) => void

  • Details:

    Triggered when Service reject, the parameters are error and params.

onBefore

  • Type: (params: P[]) => void

  • Details:

    Triggered before Service request, the parameters is params.

onAfter

  • Type: (params: P[]) => void

  • Details:

    Triggered after Service request, the parameters is params.

Last Updated: 6/6/2023, 4:05:10 AM
Contributors: John