From 3469a6a65721dccc563c345f302885d4a6e2930a Mon Sep 17 00:00:00 2001 From: bloodyowl Date: Tue, 29 Oct 2024 16:12:18 +0100 Subject: [PATCH] Add AsyncData hooks --- src/react/usePagination.ts | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/src/react/usePagination.ts b/src/react/usePagination.ts index 714c19d..003d937 100644 --- a/src/react/usePagination.ts +++ b/src/react/usePagination.ts @@ -1,5 +1,5 @@ import { DocumentNode } from "@0no-co/graphql.web"; -import { Option, Result } from "@swan-io/boxed"; +import { AsyncData, Option, Result } from "@swan-io/boxed"; import { useCallback, useContext, useRef, useSyncExternalStore } from "react"; import { match } from "ts-pattern"; import { Connection } from "../types"; @@ -180,3 +180,33 @@ const createPaginationHook = (direction: mode) => { export const useForwardPagination = createPaginationHook("after"); export const useBackwardPagination = createPaginationHook("before"); + +export const useForwardAsyncDataPagination = < + A, + E, + T extends AsyncData, E>>, +>( + connection: T, +): T => { + const data = connection + .toOption() + .flatMap((result) => result.toOption()) + .toNull(); + const patchedData = useForwardPagination(data); + return connection.mapOk(() => patchedData) as T; +}; + +export const useBackwardAsyncDataPagination = < + A, + E, + T extends AsyncData, E>>, +>( + connection: T, +): T => { + const data = connection + .toOption() + .flatMap((result) => result.toOption()) + .toNull(); + const patchedData = useBackwardPagination(data); + return connection.mapOk(() => patchedData) as T; +};