@tanstack/vue-query
Version:
Hooks for managing, caching and syncing asynchronous and remote data in Vue
63 lines • 1.86 kB
JavaScript
// src/useMutation.ts
import {
computed,
getCurrentScope,
onScopeDispose,
reactive,
readonly,
shallowReactive,
shallowReadonly,
toRefs,
watch
} from "vue-demi";
import { MutationObserver, shouldThrowError } from "@tanstack/query-core";
import { cloneDeepUnref, updateState } from "./utils.js";
import { useQueryClient } from "./useQueryClient.js";
function useMutation(mutationOptions, queryClient) {
if (process.env.NODE_ENV === "development") {
if (!getCurrentScope()) {
console.warn(
'vue-query composable like "useQuery()" should only be used inside a "setup()" function or a running effect scope. They might otherwise lead to memory leaks.'
);
}
}
const client = queryClient || useQueryClient();
const options = computed(() => {
return client.defaultMutationOptions(cloneDeepUnref(mutationOptions));
});
const observer = new MutationObserver(client, options.value);
const state = options.value.shallow ? shallowReactive(observer.getCurrentResult()) : reactive(observer.getCurrentResult());
const unsubscribe = observer.subscribe((result) => {
updateState(state, result);
});
const mutate = (variables, mutateOptions) => {
observer.mutate(variables, mutateOptions).catch(() => {
});
};
watch(options, () => {
observer.setOptions(options.value);
});
onScopeDispose(() => {
unsubscribe();
});
const readonlyState = options.value.shallow ? shallowReadonly(state) : readonly(state);
const resultRefs = toRefs(readonlyState);
watch(
() => state.error,
(error) => {
if (error && shouldThrowError(options.value.throwOnError, [error])) {
throw error;
}
}
);
return {
...resultRefs,
mutate,
mutateAsync: state.mutate,
reset: state.reset
};
}
export {
useMutation
};
//# sourceMappingURL=useMutation.js.map