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-asyncvue 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.:nameplaceholders in the url are replaced by the matching param.getparams are sent in the query string, the other methods send them as JSON, or asFormDatawithsendAs: 'multipart'(files upload).- A JSON response (
Content-Typecontainingjson) 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, ... }.urlcan 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'sfalse.
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?)
paramsis a value, a ref, a computed or a getter. With several arguments, use an array:useAsync(getSummary, () => [props.id, grpBy.value]).funcis called again each time the params change.funcis not called whileenabledisfalse, and is called as soon as it turnstrue.- Params are type-checked against
funcsignature.
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 everythingcacheSize() 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.valuethen!!gisn't recognised. - Params that
funcaccepts as nullish (optional, default value,| undefined) are skipped. - Only inline getters (
() => [a, b],() => a) and functionenabledare analysed.
Types
Main types exported: XhrGet<T> (promise with abortXhr), XhrConfig, GetReturn<T>, CacheDuration, Obj.
