@daysnap/vue-use
Version:
daysnap vue hooks
59 lines (58 loc) • 2.4 kB
JavaScript
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { isFunction } from '@daysnap/utils';
import { onActivated, onBeforeMount, ref } from 'vue';
export function useAsyncTask(task, options) {
const { initialValue, immediate, activated, throwError, onError, initialParams } = options !== null && options !== void 0 ? options : {};
const data = ref(initialValue);
const error = ref();
const loading = ref(false);
const trigger = (...args) => __awaiter(this, void 0, void 0, function* () {
var _a;
try {
error.value = undefined;
loading.value = true;
data.value = yield task(...args);
return data.value;
}
catch (err) {
if ((_a = (yield (onError === null || onError === void 0 ? void 0 : onError(err)))) !== null && _a !== void 0 ? _a : true) {
error.value = err;
const isThrow = isFunction(throwError) ? throwError() : throwError;
if (isThrow) {
throw err;
}
}
}
finally {
loading.value = false;
}
});
const init = () => __awaiter(this, void 0, void 0, function* () {
const args = isFunction(initialParams) ? initialParams() : initialParams !== null && initialParams !== void 0 ? initialParams : [];
yield trigger(...args);
});
onBeforeMount(() => __awaiter(this, void 0, void 0, function* () {
if (immediate) {
yield init();
}
}));
onActivated(() => __awaiter(this, void 0, void 0, function* () {
if (activated) {
yield init();
}
}));
return {
data,
error,
loading,
trigger,
};
}