|
1 | 1 | 'use client'; |
2 | 2 |
|
3 | | -import { useMutation, useQueryClient } from '@tanstack/react-query'; |
| 3 | +import { |
| 4 | + InfiniteData, |
| 5 | + useMutation, |
| 6 | + useQueryClient, |
| 7 | +} from '@tanstack/react-query'; |
4 | 8 | import { agentRPCNonStreaming } from 'agentex/lib'; |
5 | 9 |
|
6 | 10 | import { toast } from '@/components/agentex/toast'; |
7 | 11 |
|
8 | 12 | import { tasksKeys } from './use-tasks'; |
9 | 13 |
|
10 | 14 | import type AgentexSDK from 'agentex'; |
11 | | -import type { Task } from 'agentex/resources'; |
| 15 | +import type { Task, TaskListResponse } from 'agentex/resources'; |
12 | 16 |
|
13 | 17 | type CreateTaskParams = { |
14 | 18 | agentName: string; |
@@ -51,16 +55,37 @@ export function useCreateTask({ |
51 | 55 |
|
52 | 56 | return response.result; |
53 | 57 | }, |
54 | | - onSuccess: newTask => { |
55 | | - // Add new task to the unfiltered cache |
56 | | - queryClient.setQueryData<Task[]>(tasksKeys.all, old => { |
57 | | - if (!old) return [newTask]; |
58 | | - // Avoid duplicates |
59 | | - if (old.some(t => t.id === newTask.id)) { |
60 | | - return old; |
61 | | - } |
62 | | - return [...old, newTask]; // Add to end (will be reversed in UI to show first) |
63 | | - }); |
| 58 | + onSuccess: (newTask, variables) => { |
| 59 | + // Helper function to update infinite query cache |
| 60 | + const updateInfiniteCache = (queryKey: readonly unknown[]) => { |
| 61 | + queryClient.setQueryData<InfiniteData<TaskListResponse>>( |
| 62 | + queryKey, |
| 63 | + old => { |
| 64 | + if (!old) { |
| 65 | + // If no cache exists, create initial structure |
| 66 | + return { |
| 67 | + pages: [[newTask]], |
| 68 | + pageParams: [1], |
| 69 | + }; |
| 70 | + } |
| 71 | + |
| 72 | + // Add new task to the first page (prepend to show at top) |
| 73 | + const firstPage = old.pages[0] ?? []; |
| 74 | + if (firstPage.some(t => t.id === newTask.id)) { |
| 75 | + return old; // Avoid duplicates |
| 76 | + } |
| 77 | + |
| 78 | + return { |
| 79 | + ...old, |
| 80 | + pages: [[newTask, ...firstPage], ...old.pages.slice(1)], |
| 81 | + }; |
| 82 | + } |
| 83 | + ); |
| 84 | + }; |
| 85 | + |
| 86 | + // Update both the agent-specific cache and the generic "all tasks" cache |
| 87 | + updateInfiniteCache(tasksKeys.byAgentName(variables.agentName)); |
| 88 | + updateInfiniteCache(tasksKeys.all); |
64 | 89 |
|
65 | 90 | // Invalidate all task queries to ensure consistency |
66 | 91 | queryClient.invalidateQueries({ queryKey: tasksKeys.all }); |
|
0 commit comments