Spaces:
Paused
Paused
File size: 1,725 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 { credentialApi } from '../api';
import type { CredentialRecord, CreateCredentialRequest, UpdateCredentialRequest } from '../api';
/**
* Manages API key credentials with CRUD operations.
* Fetches on mount and automatically re-fetches after each mutation.
*/
export function useCredentials() {
const [credentials, setCredentials] = useState<CredentialRecord[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);
const refetch = useCallback(async () => {
setLoading(true);
setError(null);
try {
const res = await credentialApi.list();
setCredentials(res.credentials);
} catch (e) {
setError(e as Error);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
refetch();
}, [refetch]);
/** Stores a new credential and refreshes the list. */
const create = useCallback(
async (body: CreateCredentialRequest) => {
const res = await credentialApi.create(body);
await refetch();
return res;
},
[refetch],
);
/** Replaces a credential's payload and refreshes the list. */
const update = useCallback(
async (credentialId: string, body: UpdateCredentialRequest) => {
const res = await credentialApi.update(credentialId, body);
await refetch();
return res;
},
[refetch],
);
/** Permanently deletes a credential and refreshes the list. */
const remove = useCallback(
async (credentialId: string) => {
await credentialApi.delete(credentialId);
await refetch();
},
[refetch],
);
return { credentials, loading, error, refetch, create, update, remove };
}
|