refactor: 移除操作后刷新逻辑,依赖客户端状态同步

- 为 todo 相关的创建、更新和删除操作配置默认的 onSuccess 回调,以自动失效列表查询缓存。
- 移除所有操作后的刷新查询逻辑,依赖客户端状态自动同步更新。
This commit is contained in:
2026-01-18 04:21:57 +08:00
parent 5c55644c57
commit c7be8bd358
2 changed files with 35 additions and 29 deletions

View File

@@ -24,4 +24,30 @@ const getORPCClient = createIsomorphicFn()
const client: RouterClient = getORPCClient() 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() })
},
},
},
},
},
})

View File

@@ -15,6 +15,7 @@ function Todos() {
const [newTodoTitle, setNewTodoTitle] = useState('') const [newTodoTitle, setNewTodoTitle] = useState('')
const listQuery = useSuspenseQuery(orpc.todo.list.queryOptions()) const listQuery = useSuspenseQuery(orpc.todo.list.queryOptions())
const createMutation = useMutation(orpc.todo.create.mutationOptions()) const createMutation = useMutation(orpc.todo.create.mutationOptions())
const updateMutation = useMutation(orpc.todo.update.mutationOptions()) const updateMutation = useMutation(orpc.todo.update.mutationOptions())
const deleteMutation = useMutation(orpc.todo.remove.mutationOptions()) const deleteMutation = useMutation(orpc.todo.remove.mutationOptions())
@@ -22,15 +23,8 @@ function Todos() {
const handleCreateTodo = (e: FormEvent<HTMLFormElement>) => { const handleCreateTodo = (e: FormEvent<HTMLFormElement>) => {
e.preventDefault() e.preventDefault()
if (newTodoTitle.trim()) { if (newTodoTitle.trim()) {
createMutation.mutate( createMutation.mutate({ title: newTodoTitle.trim() })
{ title: newTodoTitle.trim() },
{
onSuccess: () => {
setNewTodoTitle('') setNewTodoTitle('')
listQuery.refetch()
},
},
)
} }
} }
@@ -39,28 +33,14 @@ function Todos() {
} }
const handleToggleTodo = (id: string, currentCompleted: boolean) => { const handleToggleTodo = (id: string, currentCompleted: boolean) => {
updateMutation.mutate( updateMutation.mutate({
{
id, id,
data: { completed: !currentCompleted }, data: { completed: !currentCompleted },
}, })
{
onSuccess: () => {
listQuery.refetch()
},
},
)
} }
const handleDeleteTodo = (id: string) => { const handleDeleteTodo = (id: string) => {
deleteMutation.mutate( deleteMutation.mutate({ id })
{ id },
{
onSuccess: () => {
listQuery.refetch()
},
},
)
} }
const todos = listQuery.data const todos = listQuery.data