useDbList.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { useCallback, useEffect, useState } from "react";
  2. import { openDB, IndexNames, StoreNames, StoreValue } from "idb";
  3. import { NovelDb } from "libs/db/getDb";
  4. import { getList } from "libs/db/history";
  5. export default function useDbList<
  6. N extends StoreNames<NovelDb>,
  7. R extends [any, any, boolean?, boolean?]
  8. >(
  9. storeName: N,
  10. index?: IndexNames<NovelDb, N>,
  11. direction: IDBCursorDirection = "next",
  12. rage?: R
  13. ) {
  14. const [isLoading, setIsLoading] = useState(false);
  15. const [
  16. { list = [], ...pages } = { page: 0, pageSize: 0, total: 0 } as PageList<
  17. NovelDb[N]["value"]
  18. >,
  19. setData,
  20. ] = useState<PageList<NovelDb[N]["value"]>>();
  21. const handleGetList = useCallback(
  22. (page: number) => {
  23. if (isLoading) return;
  24. setIsLoading(true);
  25. getList(storeName, index, page, 20, direction, rage).then((data) => {
  26. setData(data);
  27. setIsLoading(false);
  28. });
  29. },
  30. [storeName, direction, index, isLoading, rage]
  31. );
  32. useEffect(() => {
  33. if (!isLoading && pages.pageSize === 0) {
  34. handleGetList(0);
  35. }
  36. }, [handleGetList, isLoading, pages.pageSize]);
  37. return [list, pages, handleGetList, isLoading] as [
  38. typeof list,
  39. typeof pages,
  40. typeof handleGetList,
  41. typeof isLoading
  42. ];
  43. }
  44. export const useHistoryList = () =>
  45. useDbList("history", "historyIsReading", "prev", [
  46. [1, 0],
  47. [1, new Date()],
  48. ]);
  49. export const useFavoriteList = () =>
  50. useDbList("history", "historyIsFavorite", "prev", [1, 1]);