|
| 1 | +import { useParams } from "react-router-dom"; |
| 2 | +import SnippetCard from "./SnippetCard"; |
| 3 | +import { LanguageData, SnippetType } from "../types"; |
| 4 | +import { useEffect, useState } from "react"; |
| 5 | +import { getCategoryNames, getSnippetsByCategory } from "../utils/filters"; |
| 6 | +import slugify from "../utils/slugify"; |
| 7 | + |
| 8 | +const SnippetList = () => { |
| 9 | + const { language, category } = useParams(); |
| 10 | + const [snippets, setSnippets] = useState<SnippetType[] | null>(null); |
| 11 | + const [categoryTitle, setCategoryTitle] = useState<string>(""); |
| 12 | + |
| 13 | + useEffect(() => { |
| 14 | + const fetchSnippets = async () => { |
| 15 | + try { |
| 16 | + const res = await fetch(`/data/${language}.json`); |
| 17 | + if (!res.ok) { |
| 18 | + throw new Error("Failed to fetch languages in SnippetList.tsx"); |
| 19 | + } |
| 20 | + const data: LanguageData = await res.json(); |
| 21 | + |
| 22 | + const filteredCategoryTitle = getCategoryNames(data).find( |
| 23 | + (item) => slugify(item) === slugify(category || "") |
| 24 | + ); |
| 25 | + setCategoryTitle(filteredCategoryTitle || ""); |
| 26 | + |
| 27 | + // TODO: instead of "", use default category as fallback |
| 28 | + const filteredSnippets = getSnippetsByCategory(data, category || ""); |
| 29 | + setSnippets(filteredSnippets); |
| 30 | + } catch (error) { |
| 31 | + console.error("Error occured with SnippetList.tsx: ", error); |
| 32 | + } |
| 33 | + }; |
| 34 | + |
| 35 | + fetchSnippets(); |
| 36 | + }, [category]); |
| 37 | + |
| 38 | + if (!snippets) return <div>empty</div>; |
| 39 | + |
| 40 | + return ( |
| 41 | + <section className="flow"> |
| 42 | + <h2 className="section-title">{categoryTitle}</h2> |
| 43 | + <ul role="list" className="snippets"> |
| 44 | + {snippets.map((snippet) => ( |
| 45 | + <SnippetCard |
| 46 | + key={snippet.title} |
| 47 | + language={language || ""} |
| 48 | + category={category || ""} |
| 49 | + {...snippet} |
| 50 | + /> |
| 51 | + ))} |
| 52 | + </ul> |
| 53 | + </section> |
| 54 | + ); |
| 55 | +}; |
| 56 | + |
| 57 | +export default SnippetList; |
0 commit comments