refactor(command-palette): consolidate fetch source hooks behind useApiSource

This commit is contained in:
simosmik
2026-04-30 07:47:46 +00:00
parent 95ad7272e9
commit f1d7df2b1e
5 changed files with 130 additions and 153 deletions

View File

@@ -1,7 +1,7 @@
import { useEffect, useState } from 'react';
import { authenticatedFetch } from '../../../utils/api';
import { useApiSource } from './useApiSource';
export type CommitResult = {
hash: string;
shortHash: string;
@@ -15,44 +15,21 @@ interface CommitsResponse {
}
export function useCommitsSource(projectId: string | undefined, enabled: boolean) {
const [items, setItems] = useState<CommitResult[]>([]);
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
if (!enabled || !projectId) {
setItems([]);
return;
}
let cancelled = false;
setIsLoading(true);
const params = new URLSearchParams({ project: projectId, limit: '50' });
authenticatedFetch(`/api/git/commits?${params.toString()}`)
.then((r) => r.json() as Promise<CommitsResponse>)
.then((data) => {
if (cancelled) return;
if (!data.commits) {
setItems([]);
return;
}
setItems(
data.commits.map<CommitResult>((c) => ({
hash: c.hash,
shortHash: c.hash.slice(0, 7),
message: c.message,
author: c.author,
})),
);
})
.catch(() => {
if (!cancelled) setItems([]);
})
.finally(() => {
if (!cancelled) setIsLoading(false);
});
return () => {
cancelled = true;
};
}, [projectId, enabled]);
return { items, isLoading };
return useApiSource<CommitResult, CommitsResponse>({
enabled: enabled && !!projectId,
deps: [projectId],
fetcher: (signal) => {
const params = new URLSearchParams({ project: projectId!, limit: '50' });
return authenticatedFetch(`/api/git/commits?${params.toString()}`, { signal });
},
parse: (data) => {
if (!data.commits) return [];
return data.commits.map<CommitResult>((c) => ({
hash: c.hash,
shortHash: c.hash.slice(0, 7),
message: c.message,
author: c.author,
}));
},
});
}