All files / src/hooks/common useCachedListV2.ts

0% Statements 0/29
0% Branches 0/15
0% Functions 0/10
0% Lines 0/29

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                                                       
import { useDynamicTheme } from "@theme/hooks/useDynamicTheme";
import { isArray } from "lodash";
import { useEffect, useState } from "react";
import { QueryKey, useQueryClient } from "react-query";
 
type TCustomQueryFilter = {
  filterKey: string; // The key to filter against in the query key array
  filterAgainst: number; // The index of the key in the query key array to filter against
};
 
const matchesFilter = (queryKey: QueryKey, qFilter: TCustomQueryFilter[]) => {
  return qFilter.every(
    (query) => queryKey[query.filterAgainst] === query.filterKey,
  );
};
 
export const useCachedListV2 = <T>(
  queryKey: QueryKey,
  enabledCache = false,
  queryFilter?: TCustomQueryFilter[],
) => {
  const client = useQueryClient();
  const { isWideView } = useDynamicTheme();
  const shouldEnabledCache = enabledCache || !isWideView;
 
  const [allData, setAllData] = useState<T[]>([]);
 
  const updateData = (qFilter?: TCustomQueryFilter[]) => {
    const caches = client.getQueryCache().findAll(queryKey);
 
    const usedCache = qFilter
      ? caches?.filter((c) => {
          if (isArray(c?.queryKey) && qFilter) {
            return matchesFilter(c.queryKey, qFilter);
          }
          return false;
        })
      : caches;
 
    const newData = usedCache.reduce((acc, v) => {
      if (v?.state?.data) {
        const iter = (v.state.data as any)?.data ?? [];
        return [...acc, ...(iter as [])];
      }
      return acc;
    }, []);
    setAllData(newData);
  };
 
  useEffect(() => {
    if (shouldEnabledCache) {
      const unsubscribe = client
        .getQueryCache()
        .subscribe(() => updateData(queryFilter));
 
      return () => {
        unsubscribe();
      };
    }
  }, [client, shouldEnabledCache, queryFilter]);
 
  const invalidateCache = () => {
    client.removeQueries([queryKey]);
  };
 
  return { allData, invalidateCache };
};