-
-
Notifications
You must be signed in to change notification settings - Fork 135
/
Copy pathuseSnippets.ts
53 lines (42 loc) · 1.63 KB
/
useSnippets.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import { useMemo } from "react";
import { useSearchParams } from "react-router-dom";
import { useAppContext } from "@contexts/AppContext";
import { CategoryType } from "@types";
import { defaultCategoryName } from "@utils/consts";
import { QueryParams } from "@utils/enums";
import { getLanguageFileName } from "@utils/languageUtils";
import { slugify } from "@utils/slugify";
import { useFetch } from "./useFetch";
export const useSnippets = () => {
const [searchParams] = useSearchParams();
const { language, subLanguage, category } = useAppContext();
const fileName = useMemo(
() => getLanguageFileName(language.name, subLanguage),
[language.name, subLanguage]
);
const { data, loading, error } = useFetch<CategoryType[]>(fileName);
const fetchedSnippets = useMemo(() => {
if (!data) {
return [];
}
// If the category is the default category, return all snippets for the given language.
const snippets =
slugify(category) === slugify(defaultCategoryName)
? data.flatMap((item) => item.snippets)
: (data.find((item) => item.name === category)?.snippets ?? []);
if (!searchParams.has(QueryParams.SEARCH)) {
return snippets;
}
return snippets.filter((item) => {
const searchTerm = (
searchParams.get(QueryParams.SEARCH) || ""
).toLowerCase();
return (
item.title.toLowerCase().includes(searchTerm) ||
item.description.toLowerCase().includes(searchTerm) ||
item.tags.some((tag) => tag.toLowerCase().includes(searchTerm))
);
});
}, [category, data, searchParams]);
return { fetchedSnippets, loading, error };
};