Skip to content

Commit

Permalink
wrap mutation side effects with actions
Browse files Browse the repository at this point in the history
  • Loading branch information
sandstone991 committed Feb 22, 2024
1 parent 2788165 commit 8f1d842
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "mobbing-query",
"description": "A very tiny wrapper around tanstack/query-core to provide observable queries inside mobx",
"author": "Ahmed Azzam",
"version": "1.0.2",
"version": "1.0.3",
"repository": {
"type": "git",
"url": "https://github.com/sandstone991/MobQ"
Expand Down
20 changes: 18 additions & 2 deletions src/Mutation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
onBecomeUnobserved,
onBecomeObserved,
computed,
runInAction,
} from 'mobx';
import {
QueryClient,
Expand Down Expand Up @@ -109,7 +110,7 @@ class _MobxMutation<
setupDispoables() {
this.mObserver = new MutationObserver(
this.queryClient,
this.mutationOptions,
this.wrapEffectsWithActions(this.mutationOptions),
);
this.dispoables.push(
...[
Expand All @@ -132,13 +133,28 @@ class _MobxMutation<
update(state: MutationObserverResult<TData, TError, TVariables, TContext>) {
this.state = state;
}
wrapEffectsWithActions(options: typeof this.mutationOptions ){
const targets = ['onSuccess', 'onError', 'onSettled', "onMutate"] as const
for(const target of targets){
if(options[target]){
const original = options[target]
// @ts-ignore
options[target] = (...args: any[]) => {
runInAction(() => {
// @ts-ignore
original(...args)
})
}
}}
return options
}
updateOptions(
options: () => MutationObserverOptions<TData, TError, TVariables, TContext>,
) {
this._queryOptions = options;
}
_updateOptions() {
this.mObserver.setOptions(this.mutationOptions);
this.mObserver.setOptions(this.wrapEffectsWithActions(this.mutationOptions));
}

dispose() {
Expand Down

0 comments on commit 8f1d842

Please sign in to comment.