在多个位置共享变更选项的最佳方法之一是使用 mutationOptions 辅助函数。在运行时,此辅助函数仅返回您传递给它的任何内容,但在与 TypeScript 一起使用时具有许多优点。您可以在一个位置定义变更的所有可能选项,并且还将获得所有选项的类型推断和类型安全。
export class QueriesService {
private http = inject(HttpClient)
updatePost(id: number) {
return mutationOptions({
mutationFn: (post: Post) => Promise.resolve(post),
mutationKey: ['updatePost', id],
onSuccess: (newPost) => {
// ^? newPost: Post
this.queryClient.setQueryData(['posts', id], newPost)
},
})
}
}
export class QueriesService {
private http = inject(HttpClient)
updatePost(id: number) {
return mutationOptions({
mutationFn: (post: Post) => Promise.resolve(post),
mutationKey: ['updatePost', id],
onSuccess: (newPost) => {
// ^? newPost: Post
this.queryClient.setQueryData(['posts', id], newPost)
},
})
}
}