File size: 1,595 Bytes
0b9dc2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import { useState, useEffect, useCallback } from 'react';

import { agentApi } from '../api';
import type { AgentRecord, CreateAgentRequest, UpdateAgentRequest } from '../api';

/**

 * Manages the full agent list with CRUD operations.

 * Fetches on mount and automatically re-fetches after each mutation.

 */
export function useAgents() {
	const [agents, setAgents] = useState<AgentRecord[]>([]);
	const [loading, setLoading] = useState(false);
	const [error, setError] = useState<Error | null>(null);

	const refetch = useCallback(async () => {
		setLoading(true);
		setError(null);
		try {
			const res = await agentApi.list();
			setAgents(res.agents);
		} catch (e) {
			setError(e as Error);
		} finally {
			setLoading(false);
		}
	}, []);

	useEffect(() => {
		refetch();
	}, [refetch]);

	/** Creates a new agent and refreshes the list. */
	const create = useCallback(
		async (body: CreateAgentRequest) => {
			const res = await agentApi.create(body);
			await refetch();
			return res;
		},
		[refetch],
	);

	/** Partially updates an agent and refreshes the list. */
	const update = useCallback(
		async (agentId: string, body: UpdateAgentRequest) => {
			const res = await agentApi.update(agentId, body);
			await refetch();
			return res;
		},
		[refetch],
	);

	/** Deletes an agent and refreshes the list. */
	const remove = useCallback(
		async (agentId: string) => {
			await agentApi.delete(agentId);
			await refetch();
		},
		[refetch],
	);

	return { agents, loading, error, refetch, create, update, remove };
}