npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

vue-use-async

v1.14.5

Published

Xhr and async helpers

Readme

vue-use-async

Xhr and async helpers for Vue 3 (composition API).

data, isPending and error are reactive, so they can be used directly in a template. Queries are re-run when their params change, can wait for an enabled condition, and are aborted when the component is unmounted.

Installation

npm install vue-use-async

vue is a peer dependency.

Xhr

Small XMLHttpRequest wrapper returning promises.

import { Xhr } from 'vue-use-async';

const users = await Xhr.new<User[]>().get({ url: '/users', params: { active: true } });

await Xhr.new().post({ url: '/users/:id', params: { id: 1, name: 'Bob' } });
  • get, post, put, delete, abort.
  • :name placeholders in the url are replaced by the matching param.
  • get params are sent in the query string, the other methods send them as JSON, or as FormData with sendAs: 'multipart' (files upload).
  • A JSON response (Content-Type containing json) is parsed.
  • Other options: token (bearer), timeout (10s by default), responseType, onStart, onEnd, onProgress, onAbort, onError.

Xhr.onBeforeSend(cb) registers a global hook to update the query params of every GET.

useXhr

Same as Xhr, but bound to the component: get returns reactive refs and every pending query is aborted on unmount.

import { useXhr } from 'vue-use-async';

export default function (props) {
  const { get, post } = useXhr({ token: computed(() => store.token) });

  const {
    data,
    isPending,
    error,
    reload,
  } = get({
    url: '/users/:id',
    cacheDuration: 200,
  }, () => ({ id: props.id }));

  const save = (user) => post({ url: '/users' }, user);

  return { data, isPending, save };
}

get(config, params?, enabled?)

  • config: a url, or { url, cacheDuration, enabled, ... }. url can also be a function of the params or a computed.
  • params: a value, a ref, a computed or a getter. The query is sent again when it changes.
  • enabled: boolean, ref or getter. Nothing is sent while it's false.

It returns data, isPending, error, promise, reload, abort, onStart, onEnd, onError and the xhr itself.

useAsync

Same idea as useXhr().get but for any function returning a promise.

import { useAsync } from 'vue-use-async';

const getUser = (id: number) => Xhr.new<User>().get({ url: '/users/:id', params: { id } });

const { data, isPending, reload } = useAsync(getUser, () => props.id);

useAsync(func, params?, enabled?)

  • params is a value, a ref, a computed or a getter. With several arguments, use an array: useAsync(getSummary, () => [props.id, grpBy.value]).
  • func is called again each time the params change.
  • func is not called while enabled is false, and is called as soon as it turns true.
  • Params are type-checked against func signature.

It returns data, isPending, error, promise, reload, onStart, onEnd and onError.

Params not yet defined

When enabled is passed, each param may be undefined | null, since func won't be called before enabled is true:

const getSummary = (id: number, grpBy: string) => Promise.resolve('ok');

const grpBy = ref<string>();

// ok: `grpBy.value` is `string | undefined`, but `enabled` is passed
useAsync(getSummary, () => [props.id, grpBy.value], () => !!grpBy.value);

// TS error: without `enabled`, params must match `getSummary` signature
useAsync(getSummary, () => [props.id, grpBy.value]);

TypeScript can't check that enabled really tests these params. The ESLint rule does.

useMutation

For writes: nothing is sent until mutate is called.

import { useMutation } from 'vue-use-async';

const {
  mutate,
  isPending,
  error,
  onEnd,
  onError,
} = useMutation(updateUser);

onEnd((res, params) => { /* ... */ });

await mutate(user);

mutate takes the same arguments as the function and returns its promise.

To type error, use useMutationWithError:

const useMutation = useMutationWithError<ApiError>();

const { mutate, error } = useMutation(updateUser); // error: Ref<null | ApiError>

useResult

data is undefined until the query is resolved. useResult gives it a default value, and an optional mapping.

import { useAsync, useResult } from 'vue-use-async';

const { data } = useAsync(getProducts);

const products = useResult(data, []);

const names = useResult(data, [], (list) => list.map((p) => p.name));

useSpinner

Keeps isPending to true for a minimum duration (400ms by default), so a spinner doesn't blink.

import { useAsync, useSpinner } from 'vue-use-async';

const { isPending } = useAsync(getProducts);

const showSpinner = useSpinner(isPending, 300);

cache

Memoizes a promise by id. While a query with the same id is pending or cached, it's not sent again.

import { cache, clearCache } from 'vue-use-async';

const getCountries = () => cache({
  id: 'countries',
  xhr: () => Xhr.new<Country[]>().get({ url: '/countries' }),
  duration: 'max', // in ms, 'max' is 1h. 200ms by default
});

clearCache('countries'); // or `clearCache()` for everything

cacheSize() and cacheIds() are also exported, mostly for debugging.

Error handling

A rejected useAsync / useXhr query sets error and calls the onError callbacks. The error is also re-thrown, so it can be captured by a parent component with onErrorCaptured.

ESLint

vue-use-async/eslint is a flat-config plugin. It needs TypeScript type information (parserOptions.projectService).

// eslint.config.ts
import vueUseAsyncPlugin from 'vue-use-async/eslint';

export default [
  // ...
  vueUseAsyncPlugin,
];

vue-use-async/use-async-guarded-args

Each param of useAsync that may be undefined | null must be tested in the enabled callback.

// ok
useAsync(getSummary, () => [props.id, grpBy.value], () => !!grpBy.value);

// error: "grpBy.value" may be undefined but is not tested in the `enabled` callback of `useAsync`
useAsync(getSummary, () => [props.id, grpBy.value], () => true);
  • Tests recognised: !x, !!x, x && ..., x || ..., ternary, x !== undefined, x != null, Boolean(x).
  • The match is done on the source text: const g = grpBy.value then !!g isn't recognised.
  • Params that func accepts as nullish (optional, default value, | undefined) are skipped.
  • Only inline getters (() => [a, b], () => a) and function enabled are analysed.

Types

Main types exported: XhrGet<T> (promise with abortXhr), XhrConfig, GetReturn<T>, CacheDuration, Obj.