UNPKG

@tanstack/query-core

Version:

The framework agnostic core that powers TanStack Query

102 lines 3.24 kB
// src/mutationObserver.ts import { getDefaultState } from "./mutation.js"; import { notifyManager } from "./notifyManager.js"; import { Subscribable } from "./subscribable.js"; import { hashKey, shallowEqualObjects } from "./utils.js"; var MutationObserver = class extends Subscribable { #client; #currentResult = void 0; #currentMutation; #mutateOptions; constructor(client, options) { super(); this.#client = client; this.setOptions(options); this.bindMethods(); this.#updateResult(); } bindMethods() { this.mutate = this.mutate.bind(this); this.reset = this.reset.bind(this); } setOptions(options) { const prevOptions = this.options; this.options = this.#client.defaultMutationOptions(options); if (!shallowEqualObjects(this.options, prevOptions)) { this.#client.getMutationCache().notify({ type: "observerOptionsUpdated", mutation: this.#currentMutation, observer: this }); } if (prevOptions?.mutationKey && this.options.mutationKey && hashKey(prevOptions.mutationKey) !== hashKey(this.options.mutationKey)) { this.reset(); } else if (this.#currentMutation?.state.status === "pending") { this.#currentMutation.setOptions(this.options); } } onUnsubscribe() { if (!this.hasListeners()) { this.#currentMutation?.removeObserver(this); } } onMutationUpdate(action) { this.#updateResult(); this.#notify(action); } getCurrentResult() { return this.#currentResult; } reset() { this.#currentMutation?.removeObserver(this); this.#currentMutation = void 0; this.#updateResult(); this.#notify(); } mutate(variables, options) { this.#mutateOptions = options; this.#currentMutation?.removeObserver(this); this.#currentMutation = this.#client.getMutationCache().build(this.#client, this.options); this.#currentMutation.addObserver(this); return this.#currentMutation.execute(variables); } #updateResult() { const state = this.#currentMutation?.state ?? getDefaultState(); this.#currentResult = { ...state, isPending: state.status === "pending", isSuccess: state.status === "success", isError: state.status === "error", isIdle: state.status === "idle", mutate: this.mutate, reset: this.reset }; } #notify(action) { notifyManager.batch(() => { if (this.#mutateOptions && this.hasListeners()) { const variables = this.#currentResult.variables; const context = this.#currentResult.context; if (action?.type === "success") { this.#mutateOptions.onSuccess?.(action.data, variables, context); this.#mutateOptions.onSettled?.(action.data, null, variables, context); } else if (action?.type === "error") { this.#mutateOptions.onError?.(action.error, variables, context); this.#mutateOptions.onSettled?.( void 0, action.error, variables, context ); } } this.listeners.forEach((listener) => { listener(this.#currentResult); }); }); } }; export { MutationObserver }; //# sourceMappingURL=mutationObserver.js.map