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 69 | 119x 196x 196x 196x 196x 196x 196x 95x 87x 87x 95x 87x 19x 19x 68x 95x 196x 95x 95x 196x 32x 16x 793x 793x 793x 95x 16x 16x 196x 18x 196x | import { useDynamicTheme } from "@theme/hooks/useDynamicTheme";
import { useEffect, useRef, useState } from "react";
import { useQueryClient } from "react-query";
export const useCachedList = <T>(
queryKey: string,
enabledCache = false,
page?: number,
) => {
const client = useQueryClient();
const { isWideView } = useDynamicTheme();
const shouldEnabledCache = enabledCache || !isWideView;
const [allData, setAllData] = useState<T[]>([]);
const currentPage = useRef<number>(1);
const updateData = () => {
const caches = client.getQueryCache().findAll(queryKey, {
predicate: (query) => {
const queryKey = query.queryKey[0] as string | undefined;
return queryKey?.startsWith(queryKey) ?? false; //if the computed key doesn't start with the query string, solve this problem at usage and not the abstraction
},
});
const newData = caches.reduce((acc, v) => {
if (v?.state?.data) {
const iter = (v.state.data as any)?.data ?? [];
return [...acc, ...(iter as [])];
}
return acc;
}, []);
setAllData(newData);
};
const subscribeToPageChanged = () => {
if (page === 1) {
updateData();
} else Eif (page !== undefined && page !== currentPage.current) {
updateData();
currentPage.current = page;
}
};
useEffect(() => {
if (shouldEnabledCache) {
const unsubscribe = client.getQueryCache().subscribe((listener) => {
const key = listener?.query.queryHash;
const is = key?.includes(queryKey);
if (is) {
subscribeToPageChanged();
}
});
return () => {
unsubscribe();
};
}
}, [client, shouldEnabledCache]);
const invalidateCache = () => {
client.removeQueries([queryKey]);
};
return { allData, invalidateCache };
};
|