From c7be8bd3588e4bcf3f1de850ea94f66f444d4b02 Mon Sep 17 00:00:00 2001 From: imbytecat Date: Sun, 18 Jan 2026 04:21:57 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E7=A7=BB=E9=99=A4=E6=93=8D?= =?UTF-8?q?=E4=BD=9C=E5=90=8E=E5=88=B7=E6=96=B0=E9=80=BB=E8=BE=91=EF=BC=8C?= =?UTF-8?q?=E4=BE=9D=E8=B5=96=E5=AE=A2=E6=88=B7=E7=AB=AF=E7=8A=B6=E6=80=81?= =?UTF-8?q?=E5=90=8C=E6=AD=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 为 todo 相关的创建、更新和删除操作配置默认的 onSuccess 回调,以自动失效列表查询缓存。 - 移除所有操作后的刷新查询逻辑,依赖客户端状态自动同步更新。 --- src/orpc/client.ts | 28 +++++++++++++++++++++++++++- src/routes/todos.tsx | 36 ++++++++---------------------------- 2 files changed, 35 insertions(+), 29 deletions(-) diff --git a/src/orpc/client.ts b/src/orpc/client.ts index 8de2d89..b5d0e8f 100644 --- a/src/orpc/client.ts +++ b/src/orpc/client.ts @@ -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() }) + }, + }, + }, + }, + }, +}) diff --git a/src/routes/todos.tsx b/src/routes/todos.tsx index 9b88e46..3112308 100644 --- a/src/routes/todos.tsx +++ b/src/routes/todos.tsx @@ -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) => { e.preventDefault() if (newTodoTitle.trim()) { - createMutation.mutate( - { title: newTodoTitle.trim() }, - { - onSuccess: () => { - setNewTodoTitle('') - listQuery.refetch() - }, - }, - ) + createMutation.mutate({ title: newTodoTitle.trim() }) + setNewTodoTitle('') } } @@ -39,28 +33,14 @@ function Todos() { } const handleToggleTodo = (id: string, currentCompleted: boolean) => { - updateMutation.mutate( - { - id, - data: { completed: !currentCompleted }, - }, - { - onSuccess: () => { - listQuery.refetch() - }, - }, - ) + updateMutation.mutate({ + id, + data: { completed: !currentCompleted }, + }) } const handleDeleteTodo = (id: string) => { - deleteMutation.mutate( - { id }, - { - onSuccess: () => { - listQuery.refetch() - }, - }, - ) + deleteMutation.mutate({ id }) } const todos = listQuery.data