summaryrefslogtreecommitdiffhomepage
path: root/frontend/src/apis/queries/hooks.ts
blob: 4f84672218738cc6b4f4d9ad133b0c9165e8189a (plain)
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import { GetItemId, useOnValueChange } from "@/utilities";
import { usePageSize } from "@/utilities/storage";
import { useCallback, useEffect, useState } from "react";
import {
  QueryKey,
  useQuery,
  useQueryClient,
  UseQueryResult,
} from "react-query";
import { QueryKeys } from "./keys";

export type UsePaginationQueryResult<T extends object> = UseQueryResult<
  DataWrapperWithTotal<T>
> & {
  controls: {
    gotoPage: (index: number) => void;
  };
  paginationStatus: {
    isPageLoading: boolean;
    totalCount: number;
    pageSize: number;
    pageCount: number;
    page: number;
  };
};

export function usePaginationQuery<
  TObject extends object = object,
  TQueryKey extends QueryKey = QueryKey
>(
  queryKey: TQueryKey,
  queryFn: RangeQuery<TObject>,
  cacheIndividual = true
): UsePaginationQueryResult<TObject> {
  const client = useQueryClient();

  const [page, setIndex] = useState(0);
  const pageSize = usePageSize();

  const start = page * pageSize;

  const results = useQuery(
    [...queryKey, QueryKeys.Range, { start, size: pageSize }],
    () => {
      const param: Parameter.Range = {
        start,
        length: pageSize,
      };
      return queryFn(param);
    },
    {
      onSuccess: ({ data }) => {
        if (cacheIndividual) {
          data.forEach((item) => {
            const id = GetItemId(item);
            if (id) {
              client.setQueryData([...queryKey, id], item);
            }
          });
        }
      },
    }
  );

  const { data } = results;

  const totalCount = data?.total ?? 0;
  const pageCount = Math.ceil(totalCount / pageSize);

  const gotoPage = useCallback(
    (idx: number) => {
      if (idx >= 0 && idx < pageCount) {
        setIndex(idx);
      }
    },
    [pageCount]
  );

  const [isPageLoading, setIsPageLoading] = useState(false);

  useOnValueChange(page, () => {
    if (results.isFetching) {
      setIsPageLoading(true);
    }
  });

  useEffect(() => {
    if (!results.isFetching) {
      setIsPageLoading(false);
    }
  }, [results.isFetching]);

  // Reset page index if we out of bound
  useEffect(() => {
    if (pageCount === 0) return;

    if (page >= pageCount) {
      setIndex(pageCount - 1);
    } else if (page < 0) {
      setIndex(0);
    }
  }, [page, pageCount]);

  return {
    ...results,
    paginationStatus: {
      isPageLoading,
      totalCount,
      pageCount,
      pageSize,
      page,
    },
    controls: {
      gotoPage,
    },
  };
}