vue-request

repository·master·Indexed 23 days ago

https://github.com/attojs/vue-request

A lightweight library for managing API state in Vue 2 and 3 applications. It simplifies data fetching with built-in support for SWR, polling, error retries, caching, and pagination. Key features include the useRequest hook for general data fetching and the useLoadMore hook for infinite scrolling and paginated lists. It provides global and request-specific configuration for timing, rate limiting, and window focus re-fetching, as well as a plugin system to intercept request behavior.

Tokens
4.8K
Snippets
11
Records
30
Agent score
79%

What's inside vue-request

  1. Migrate to vue-request v2.x

    master

    If you are upgrading from v1.x to v2.x, note the following breaking changes:

    1. Service Wrapper: The service option no longer supports strings or objects directly. You must wrap your request library (e.g., axios) in a function that returns a Promise.
    2. Result Formatting: formatResult has been removed. You should handle data transformation directly within your service function.
    3. Parallel Mode: queryKey has been removed, which means parallel request mode is no longer supported. It is recommended to encapsulate each request and its UI into its own component.
    4. Ready Logic:
      • When manual=false, a request is automatically triggered whenever ready changes from false to true (using options.defaultParams).
      • When manual=true, a request cannot be initiated as long as ready is false.
    5. Async Execution: The run method no longer returns a Promise. Use runAsync instead if you need to await the result.
    6. Component Replacement: RequestConfig component has been removed. You can achieve similar results by wrapping your logic with useRequestProvider.
  2. Install VueRequest via CDN

    master

    For production environments, it is recommended to link to a specific version and build file to avoid breaking changes. Once added, the exported methods are available under window.VueRequest.

    <script src="https://unpkg.com/vue-request/dist/vue-request.min.js"></script>
  3. Install vue-request via CDN

    master

    For environments where a package manager is not used, you can include vue-request via a <script> tag from unpkg. Once added, the exported methods are available under window.VueRequest.

    <script src="https://unpkg.com/vue-request/dist/vue-request.min.js"></script>
  4. Understand the Query and State structure

    master

    When using vue-request, the core data returned is structured around a State and a FunctionContext.

    • State: Contains reactive Ref objects for loading (boolean), data (the response), error (any error encountered), and params (the arguments passed to the service).
    • FunctionContext: Provides methods to control the request lifecycle, such as runAsync (returns a promise), run (void), cancel (stops the request), refresh (re-runs the request), and mutate (manually updates the local data).
  5. Configure custom cacheKey with a function

    master
    In useRequest, the cacheKey option can accept a function. This is useful for generating dynamic keys based on the request parameters. Note that during initialization, params will be undefined, so you must handle that case to avoid errors.
  6. Enable automatic re-fetching on window focus

    master

    To ensure data stays synchronized when a user switches back to your browser tab or wakes their computer from sleep, use the refreshOnWindowFocus option. You can control the minimum interval between focus-triggered requests using refocusTimespan.

    const { data, error, run } = useRequest(getUserInfo, {
      refreshOnWindowFocus: true,
      refocusTimespan: 1000, // Request interval in milliseconds
    });
  7. Basic usage of useRequest

    master

    The useRequest hook manages the state of an asynchronous request. It accepts a service function (an async function that returns a Promise, such as one using axios) and returns reactive data, loading, and error values.

    • While loading: data is undefined and loading is true.
    • On success: data contains the result and loading is false.
    • On error: error contains the error object and loading is false.
    <template>
      <div>
        <div v-if="loading">loading...</div>
        <div v-if="error">failed to fetch</div>
        <div v-if="data">Hey! {{ data }}</div>
      </div>
    </template>
    
    <script lang="ts" setup>
    const { data, loading, error } = useRequest(service);
    </script>
  8. Refresh data on window focus

    master

    Use the refreshOnWindowFocus option to automatically re-request data when the browser window regains focus. This is useful for ensuring data consistency when users switch tabs or when a computer resumes from sleep. You can control the minimum interval between refreshes using refocusTimespan (in milliseconds).

    const { data, error, run } = useRequest(getUserInfo, {
      refreshOnWindowFocus: true,
      refocusTimespan: 1000, // refresh interval 1s
    });
  9. Use the useLoadMore API

    master

    The useLoadMore hook is used for handling infinite scroll or paginated lists where data is appended. The returned data must be an object containing a list array.

    Options

    • manual: If true, you must manually call loadMore or loadMoreAsync to trigger requests. Defaults to false.
    • ready: When manual=false, triggers refresh when ready transitions from false to true. When manual=true, prevents requests while ready is false.
    • refreshDeps: A WatchSource that triggers refresh when changed.
    • refreshDepsAction: A callback triggered when refreshDeps changes.
    • debounceInterval / debounceOptions: Configuration for debouncing requests.
    • throttleInterval / throttleOptions: Configuration for throttling requests.
    • errorRetryCount / errorRetryInterval: Configuration for automatic retries on error.
    • isNoMore: A function (data?: R) => boolean to determine if more data is available.
    • onBefore / onAfter / onSuccess / onError: Lifecycle hooks for the service execution.

    Result

    • data: The service response (must contain a list property).
    • dataList: A ref to the data.list array.
    • loading: Whether a request is in progress.
    • loadingMore: Whether a 'load more' request is in progress.
    • noMore: Whether there is no more data (based on isNoMore).
    • error: The error object if the service fails.
    • loadMore: Triggers loading more; catches errors and passes them to onError.
    • loadMoreAsync: Triggers loading more; returns a Promise (caller must handle errors).
    • refresh: Triggers loading the first page; catches errors and passes them to onError.
    • refreshAsync: Triggers loading the first page; returns a Promise (caller must handle errors).
    • mutate: Directly modifies the data result.
    • cancel: Cancels the current request.