Skip to content

Commit f5da71c

Browse files
committed
feat: add invalidateByKey mobx mutatin feature
1 parent 1af9e37 commit f5da71c

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

src/mobx-mutation.ts

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,13 @@ export class MobxMutation<
3636
constructor(
3737
protected config: MobxMutationConfig<TData, TVariables, TError, TContext>,
3838
) {
39-
const { queryClient, invalidateQueries, ...restOptions } = config;
39+
const {
40+
queryClient,
41+
invalidateQueries,
42+
invalidateByKey: providedInvalidateByKey,
43+
mutationKey,
44+
...restOptions
45+
} = config;
4046
this.abortController = new LinkedAbortController(config.abortSignal);
4147
this.queryClient = queryClient;
4248
this.result = undefined as any;
@@ -50,6 +56,12 @@ export class MobxMutation<
5056

5157
makeObservable(this);
5258

59+
const invalidateByKey =
60+
providedInvalidateByKey ??
61+
(queryClient instanceof MobxQueryClient
62+
? queryClient.mutationFeatures.invalidateByKey
63+
: null);
64+
5365
this.mutationOptions = this.queryClient.defaultMutationOptions(restOptions);
5466
this.hooks =
5567
'hooks' in this.queryClient ? this.queryClient.hooks : undefined;
@@ -102,6 +114,15 @@ export class MobxMutation<
102114
});
103115
}
104116

117+
if (invalidateByKey && mutationKey) {
118+
this.onDone(() => {
119+
this.queryClient.invalidateQueries({
120+
...(invalidateByKey === true ? {} : invalidateByKey),
121+
queryKey: mutationKey,
122+
});
123+
});
124+
}
125+
105126
config.onInit?.(this);
106127
this.hooks?.onMutationInit?.(this);
107128
}

src/mobx-mutation.types.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,15 @@ import { MobxMutation } from './mobx-mutation';
1010
import { MobxQueryClient } from './mobx-query-client';
1111

1212
export interface MobxMutationFeatures {
13+
/**
14+
* Invalidate queries by mutation key.
15+
*
16+
* - when `true`, invalidate all queries by mutation key (not exact)
17+
* - when `object`, invalidate all queries by mutation key with this additional filters
18+
*/
19+
invalidateByKey?:
20+
| boolean
21+
| Omit<InvalidateQueryFilters, 'queryKey' | 'predicate'>;
1322
/**
1423
* Reset mutation when dispose is called
1524
*

0 commit comments

Comments
 (0)