refactor: 移除操作后刷新逻辑,依赖客户端状态同步
- 为 todo 相关的创建、更新和删除操作配置默认的 onSuccess 回调,以自动失效列表查询缓存。 - 移除所有操作后的刷新查询逻辑,依赖客户端状态自动同步更新。
This commit is contained in:
@@ -24,4 +24,30 @@ const getORPCClient = createIsomorphicFn()
|
||||
|
||||
const client: RouterClient = getORPCClient()
|
||||
|
||||
export const orpc = createTanstackQueryUtils(client)
|
||||
export const orpc = createTanstackQueryUtils(client, {
|
||||
experimental_defaults: {
|
||||
todo: {
|
||||
create: {
|
||||
mutationOptions: {
|
||||
onSuccess: (_, __, ___, ctx) => {
|
||||
ctx.client.invalidateQueries({ queryKey: orpc.todo.list.key() })
|
||||
},
|
||||
},
|
||||
},
|
||||
update: {
|
||||
mutationOptions: {
|
||||
onSuccess: (_, __, ___, ctx) => {
|
||||
ctx.client.invalidateQueries({ queryKey: orpc.todo.list.key() })
|
||||
},
|
||||
},
|
||||
},
|
||||
remove: {
|
||||
mutationOptions: {
|
||||
onSuccess: (_, __, ___, ctx) => {
|
||||
ctx.client.invalidateQueries({ queryKey: orpc.todo.list.key() })
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
@@ -15,6 +15,7 @@ function Todos() {
|
||||
const [newTodoTitle, setNewTodoTitle] = useState('')
|
||||
|
||||
const listQuery = useSuspenseQuery(orpc.todo.list.queryOptions())
|
||||
|
||||
const createMutation = useMutation(orpc.todo.create.mutationOptions())
|
||||
const updateMutation = useMutation(orpc.todo.update.mutationOptions())
|
||||
const deleteMutation = useMutation(orpc.todo.remove.mutationOptions())
|
||||
@@ -22,15 +23,8 @@ function Todos() {
|
||||
const handleCreateTodo = (e: FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault()
|
||||
if (newTodoTitle.trim()) {
|
||||
createMutation.mutate(
|
||||
{ title: newTodoTitle.trim() },
|
||||
{
|
||||
onSuccess: () => {
|
||||
createMutation.mutate({ title: newTodoTitle.trim() })
|
||||
setNewTodoTitle('')
|
||||
listQuery.refetch()
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,28 +33,14 @@ function Todos() {
|
||||
}
|
||||
|
||||
const handleToggleTodo = (id: string, currentCompleted: boolean) => {
|
||||
updateMutation.mutate(
|
||||
{
|
||||
updateMutation.mutate({
|
||||
id,
|
||||
data: { completed: !currentCompleted },
|
||||
},
|
||||
{
|
||||
onSuccess: () => {
|
||||
listQuery.refetch()
|
||||
},
|
||||
},
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
const handleDeleteTodo = (id: string) => {
|
||||
deleteMutation.mutate(
|
||||
{ id },
|
||||
{
|
||||
onSuccess: () => {
|
||||
listQuery.refetch()
|
||||
},
|
||||
},
|
||||
)
|
||||
deleteMutation.mutate({ id })
|
||||
}
|
||||
|
||||
const todos = listQuery.data
|
||||
|
||||
Reference in New Issue
Block a user