refactor(contents): extract and memoize fetchInitial logic

- Refactored `fetchInitial` function to make it reusable using `useCallback`.
- Updated `ContentCard` to call `fetchInitial` via `onUpdate` prop for better reusability.
- Removed duplicate logic from `useEffect` for improved code readability and maintainability.
This commit is contained in:
Mathis HERRIOT
2026-01-21 13:42:17 +01:00
parent 8778508ced
commit 7503707ef1

View File

@@ -20,6 +20,27 @@ export function ContentList({ fetchFn, title }: ContentListProps) {
const [offset, setOffset] = React.useState(0);
const [hasMore, setHasMore] = React.useState(true);
const fetchInitial = React.useCallback(async () => {
setLoading(true);
try {
const response = await fetchFn({
limit: 10,
offset: 0,
});
setContents(response.data);
setOffset(0);
setHasMore(response.data.length === 10);
} catch (error) {
console.error("Failed to fetch contents:", error);
} finally {
setLoading(false);
}
}, [fetchFn]);
React.useEffect(() => {
fetchInitial();
}, [fetchInitial]);
const loadMore = React.useCallback(async () => {
if (!hasMore || loading) return;
@@ -46,32 +67,12 @@ export function ContentList({ fetchFn, title }: ContentListProps) {
onLoadMore: loadMore,
});
React.useEffect(() => {
const fetchInitial = async () => {
setLoading(true);
try {
const response = await fetchFn({
limit: 10,
offset: 0,
});
setContents(response.data);
setHasMore(response.data.length === 10);
} catch (error) {
console.error("Failed to fetch contents:", error);
} finally {
setLoading(false);
}
};
fetchInitial();
}, [fetchFn]);
return (
<div className="max-w-2xl mx-auto py-8 px-4 space-y-8">
{title && <h1 className="text-2xl font-bold">{title}</h1>}
<div className="flex flex-col gap-6">
{contents.map((content) => (
<ContentCard key={content.id} content={content} />
<ContentCard key={content.id} content={content} onUpdate={fetchInitial} />
))}
</div>