File size: 2,419 Bytes
9cd6ddb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
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,
  };
};