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