Skip to content

Commit 7031525

Browse files
committed
Refactor useSnippets with feedback and more
Instead of using ternary operators, I made a pure function with early returns for easier readability and maintainability. Also moved the endpoint to a const for clarity/simplicity.
1 parent 53be0bd commit 7031525

File tree

1 file changed

+19
-8
lines changed

1 file changed

+19
-8
lines changed

src/hooks/useSnippets.ts

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,28 @@ type CategoryData = {
88
snippets: SnippetType[];
99
};
1010

11+
const getSnippetsFromData = (
12+
data: CategoryData[] | null,
13+
category: string
14+
): SnippetType[] => {
15+
if (!data?.length) {
16+
return [];
17+
}
18+
19+
if (category === "All snippets") {
20+
return data.flatMap((item) => item.snippets);
21+
}
22+
23+
const categoryData = data.find((item) => item.categoryName === category);
24+
return categoryData?.snippets ?? [];
25+
};
26+
1127
export const useSnippets = () => {
1228
const { language, category } = useAppContext();
13-
const { data, loading, error } = useFetch<CategoryData[]>(
14-
`/data/${slugify(language.lang)}.json`
15-
);
29+
const endpoint = `/data/${slugify(language.lang)}.json`;
30+
const { data, loading, error } = useFetch<CategoryData[]>(endpoint);
1631

17-
const fetchedSnippets: SnippetType[] = data
18-
? category === "All snippets"
19-
? data.flatMap((item) => item.snippets)
20-
: (data.find((item) => item.categoryName === category)?.snippets ?? [])
21-
: [];
32+
const fetchedSnippets = getSnippetsFromData(data, category);
2233

2334
return { fetchedSnippets, loading, error };
2435
};

0 commit comments

Comments
 (0)