在多个地方共享 mutation options 的最佳方法之一是使用 mutationOptions 辅助函数。在运行时,这个辅助函数只会返回你传递给它的任何内容,但当与 TypeScript 结合使用时,它具有很多优势。你可以将一个 mutation 的所有可能 options 定义在一个地方,并且你还可以获得所有这些 options 的类型推断和类型安全。
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)
},
})
}
}