"use client"; import { useEffect, useRef, useState } from "react"; import { useTranslations } from "next-intl"; import { getCollectionsByWord } from "@/lib/api"; import { resolveApiErrorMessage } from "@/lib/useApiErrorMessage"; import { CollectionResult, Fetched, Language } from "@/types/api"; import { Item, ItemActions, ItemContent } from "./ui/item"; import { Skeleton } from "./ui/skeleton"; import { CollectionsListDialog } from "./collectionsListDialog"; interface CollectionsListProps { word: string; lang: Language; onResult?: (result: Fetched) => void; } type ListState = | { status: "loading" } | { status: "error"; error: unknown } | { status: "done"; collections: CollectionResult[] }; export function CollectionsList({ word, lang, onResult }: CollectionsListProps) { const [byKey, setByKey] = useState>({}); const key = `${lang}:${word}`; const state = byKey[key] ?? { status: "loading" }; const onResultRef = useRef(onResult); useEffect(() => { onResultRef.current = onResult; }); useEffect(() => { let cancelled = false; getCollectionsByWord(lang, word) .then((data) => { if (cancelled) return; setByKey((prev) => ({ ...prev, [key]: { status: "done", collections: data } })); onResultRef.current?.( Object.assign(data, { fetched_at: new Date().toISOString() }) ); }) .catch((error) => { if (cancelled) return; setByKey((prev) => ({ ...prev, [key]: { status: "error", error } })); }); return () => { cancelled = true; }; }, [lang, word, key]); const t = useTranslations("CollectionsList"); const tApi = useTranslations("ApiErrors"); const errorMessage = state.status === "error" ? resolveApiErrorMessage( state.error, (kind) => (kind === "not-found" ? t("notFound") : tApi(kind)), t("notFound") ) : null; const applyOptimistic = (collection: CollectionResult, adding: boolean) => { if (state.status !== "done") return () => {}; const previous = state.collections; setByKey((prev) => ({ ...prev, [key]: { status: "done", collections: adding ? [...previous, collection] : previous.filter((c) => c.id !== collection.id), }, })); return () => setByKey((prev) => ({ ...prev, [key]: { status: "done", collections: previous } })); }; return (
{state.status === "loading" && ( )} {state.status === "error" && (

{errorMessage}

)} {state.status === "done" && (
)}
); }