feat: add useAsync and implement it on every async mutation method

This commit is contained in:
mrjvs
2026-08-16 12:44:35 +02:00
parent cc5f85485c
commit bae28ef863
12 changed files with 236 additions and 196 deletions

View File

@@ -0,0 +1,43 @@
import { useAsyncState } from '@vueuse/core';
export type UseAsyncOptions<TResult, TArgs extends any[] = []> = {
handler(...args: TArgs): Promise<TResult>;
onSuccess?: (data: TResult) => void;
onError?: (error: any) => void;
allowParallel?: boolean;
};
export type UseAsyncResult<TResult, TArgs extends any[] = []> = {
state: Ref<TResult | null>;
isLoading: Ref<boolean>;
error: Ref<unknown>;
execute: (...args: TArgs) => Promise<void>;
};
export function useAsync<TResult, TArgs extends any[] = []>(ops: UseAsyncOptions<TResult, TArgs>): UseAsyncResult<TResult, TArgs> {
const preventDuringLoading = !ops.allowParallel;
const output = useAsyncState<TResult | null, TArgs, true>(ops.handler, null, {
immediate: false,
onSuccess(data) {
ops.onSuccess?.(data as any);
},
onError(err) {
ops.onError?.(err);
}
});
async function execute(...args: TArgs) {
if (preventDuringLoading && output.isLoading.value) {
return;
}
await output.executeImmediate(...args);
}
return {
state: output.state,
isLoading: output.isLoading,
error: output.error,
execute
};
}