mirror of
https://github.com/docmost/docmost.git
synced 2026-05-20 00:14:10 +08:00
78b1c1a453
* add cursor pagination function * support custom order modifier * refactor returned object * feat(db): migrate paginated endpoints to cursor-based pagination * sync * support hasPrevPage boolean * feat(client): migrate pagination from offset to cursor-based * support beforeCursor/prevCursor * wrap search results in items array for API consistency
35 lines
1.0 KiB
TypeScript
35 lines
1.0 KiB
TypeScript
import { useState, useRef, useCallback } from "react";
|
|
|
|
export function usePaginateAndSearch(initialQuery: string = "") {
|
|
const [search, setSearch] = useState(initialQuery);
|
|
const [cursor, setCursor] = useState<string | undefined>(undefined);
|
|
const [cursorStack, setCursorStack] = useState<(string | undefined)[]>([]);
|
|
const prevSearchRef = useRef(search);
|
|
|
|
const handleSearch = useCallback((newQuery: string) => {
|
|
if (prevSearchRef.current !== newQuery) {
|
|
prevSearchRef.current = newQuery;
|
|
setSearch(newQuery);
|
|
setCursor(undefined);
|
|
setCursorStack([]);
|
|
}
|
|
}, []);
|
|
|
|
const goNext = useCallback((nextCursor: string | null | undefined) => {
|
|
if (nextCursor) {
|
|
setCursorStack((prev) => [...prev, cursor]);
|
|
setCursor(nextCursor);
|
|
}
|
|
}, [cursor]);
|
|
|
|
const goPrev = useCallback(() => {
|
|
setCursorStack((prev) => {
|
|
const next = prev.slice(0, -1);
|
|
setCursor(prev[prev.length - 1]);
|
|
return next;
|
|
});
|
|
}, []);
|
|
|
|
return { search, cursor, goNext, goPrev, handleSearch };
|
|
}
|