UNPKG

autumn-js

Version:
90 lines (86 loc) 2.19 kB
"use client"; import { AutumnContext, useAutumnContext } from "./chunk-OYO7LPVB.mjs"; import { AutumnError } from "./chunk-QN2ALOVD.mjs"; // src/libraries/react/hooks/useListEvents.tsx import { useCallback, useState } from "react"; import useSWR from "swr"; var useListEvents = (params) => { const context = useAutumnContext({ AutumnContext, name: "useListEvents" }); const client = context.client; const limit = params.limit ?? 100; const [page, setPage] = useState(0); const startDate = params.customRange?.start ? new Date(params.customRange.start).toISOString().slice(0, 13) : void 0; const endDate = params.customRange?.end ? new Date(params.customRange.end).toISOString().slice(0, 13) : void 0; const offset = page * limit; const fetcher = async () => { const res = await client.events.list({ ...params, offset, limit }); if (res.error) { const err = new AutumnError({ message: res.error.message, code: res.error.code }); err.statusCode = res.statusCode; throw err; } return res.data; }; const { data, error, mutate, isLoading } = useSWR( ["eventList", params.featureId, startDate, endDate, offset, limit], fetcher, { dedupingInterval: 2e3, revalidateOnFocus: false, revalidateOnReconnect: false, shouldRetryOnError: (error2) => error2.statusCode === 429, errorRetryCount: 3, refreshInterval: 0, ...params.swrConfig } ); const hasMore = data?.has_more ?? false; const hasPrevious = page > 0; const nextPage = useCallback(() => { if (hasMore) { setPage((p) => p + 1); } }, [hasMore]); const prevPage = useCallback(() => { if (hasPrevious) { setPage((p) => p - 1); } }, [hasPrevious]); const goToPage = useCallback((pageNum) => { setPage(Math.max(0, pageNum)); }, []); const resetPagination = useCallback(() => { setPage(0); }, []); return { list: data?.list, hasMore, hasPrevious, page, isLoading, error, refetch: mutate, nextPage, prevPage, goToPage, resetPagination }; }; export { useListEvents };