mirror of
https://github.com/wu736139669/hapi.git
synced 2026-08-05 06:24:37 +00:00
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.
37 lines
1.1 KiB
TypeScript
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,
|
|
}
|
|
}
|