Files
hapi/web/src/hooks/mutations/useSpawnSession.ts
T
weishu 3a7272d03d feat(web): integrate TanStack Query for state management
Replace manual state management with TanStack Query (React Query) for more robust server state handling. This refactoring introduces:

- New hooks for queries: useSessions, useSession, useMessages, useMachines
- New hooks for mutations: useSendMessage, useSessionActions, useSpawnSession
- Centralized query client with optimized configuration (5s staleTime, disabled window focus refetch)
- Query key factory for consistent cache invalidation
- Improved message synchronization via socket events with cache updates
- Optimistic updates for message sending with retry capability
- Simplified App.tsx by removing manual state management logic
- Integrated React Query devtools in development mode

This enables automatic cache management, better error handling, and a foundation for more sophisticated data fetching patterns.
2025-12-19 18:25:13 +08:00

37 lines
1.1 KiB
TypeScript

import { useMutation, useQueryClient } from '@tanstack/react-query'
import type { ApiClient } from '@/api/client'
import type { SpawnResponse } from '@/types/api'
import { queryKeys } from '@/lib/query-keys'
type SpawnInput = {
machineId: string
directory: string
agent?: 'claude' | 'codex'
}
export function useSpawnSession(api: ApiClient | null): {
spawnSession: (input: SpawnInput) => Promise<SpawnResponse>
isPending: boolean
error: string | null
} {
const queryClient = useQueryClient()
const mutation = useMutation({
mutationFn: async (input: SpawnInput) => {
if (!api) {
throw new Error('API unavailable')
}
return await api.spawnSession(input.machineId, input.directory, input.agent)
},
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: queryKeys.sessions })
},
})
return {
spawnSession: mutation.mutateAsync,
isPending: mutation.isPending,
error: mutation.error instanceof Error ? mutation.error.message : mutation.error ? 'Failed to spawn session' : null,
}
}