Spaces:
Running
Running
| import { useState } from "react"; | |
| import { useQuery } from "react-query"; | |
| import { useMount, useUpdateEffect } from "react-use"; | |
| import { Icons } from "components/svg/icons"; | |
| import { IconItem } from "types/editor"; | |
| export const useSearch = (searchValue: string, tags: string[]) => { | |
| const { data, refetch } = useQuery("icons", () => { | |
| const res = new Set(); | |
| Icons.map((icon: IconItem) => { | |
| if (tags?.length === 0 && !searchValue) return res.add(icon); | |
| if (tags?.length === 0 && searchValue) { | |
| if ( | |
| searchValue !== "" && | |
| icon.tags.join("").includes(searchValue.toLowerCase()) | |
| ) { | |
| res.add(icon); | |
| } | |
| } | |
| if (tags?.length > 0 && !searchValue) { | |
| if (icon?.category && tags.includes(icon.category as string)) { | |
| res.add(icon); | |
| } | |
| } | |
| if (tags?.length > 0 && searchValue) { | |
| if ( | |
| icon?.category && | |
| tags.includes(icon.category as string) && | |
| icon.tags.join("").includes(searchValue.toLowerCase()) | |
| ) { | |
| res.add(icon); | |
| } | |
| } | |
| }); | |
| return Array.from(res).flat(); | |
| }); | |
| useUpdateEffect(() => { | |
| refetch(); | |
| }, [searchValue, tags]); | |
| return data; | |
| }; | |
| export const useSingleSearch = (searchValue: string) => { | |
| const { data, refetch } = useQuery("icons", () => { | |
| const res = new Set(); | |
| Icons.map((icon: IconItem) => { | |
| if ( | |
| searchValue !== "" && | |
| icon.tags.join("").includes(searchValue.toLowerCase()) | |
| ) { | |
| res.add(icon); | |
| } else if (!searchValue) { | |
| res.add(icon); | |
| } | |
| }); | |
| return Array.from(res).flat(); | |
| }); | |
| useUpdateEffect(() => { | |
| refetch(); | |
| }, [searchValue]); | |
| return data; | |
| }; | |
| export const useResults = (perPage = 84) => { | |
| const { data } = useQuery("icons", (datas: any) => datas); | |
| const [page, setPage] = useState(1); | |
| const [resultsPerPage] = useState(perPage); | |
| const indexOfLastResult = page * resultsPerPage; | |
| const indexOfFirstResult = indexOfLastResult - resultsPerPage; | |
| const currentResults = Array.isArray(data) | |
| ? data?.slice(indexOfFirstResult, indexOfLastResult) | |
| : []; | |
| const maxPage = Math.ceil(data?.length / resultsPerPage); | |
| const totalItems = data?.length; | |
| useUpdateEffect(() => { | |
| setPage(1); | |
| }, [data]); | |
| return { | |
| results: currentResults, | |
| page, | |
| setPage, | |
| maxPage, | |
| totalItems, | |
| }; | |
| }; | |