import { useQueryClient } from "@tanstack/react-query"; import { useState } from "react"; import { brokerageOperationsQueryOptions, type OperationCategory, useBrokerageOperations, } from "@/entities/broker-operation"; import { ApiErrorCode, apiErrorCode, isApiErrorCode } from "@/shared/api"; function useInstrumentOperations( uid: string, filter: string, categories: OperationCategory[], ) { const scope = `${uid}:${filter}`; const [pagination, setPagination] = useState<{ cursors: string[]; scope: string; }>({ cursors: [], scope }); const cursors = pagination.scope === scope ? pagination.cursors : []; const client = useQueryClient(); const firstPage = { categories, instrumentUid: uid, limit: 20 }; const operations = useBrokerageOperations(uid ? "all" : undefined, { ...firstPage, cursor: cursors.at(-1), }); const retry = (retryScreen: () => unknown) => { if ( isApiErrorCode( apiErrorCode(operations.error), ApiErrorCode.InvalidOperationsCursor, ) ) { setPagination({ cursors: [], scope }); void client.invalidateQueries({ exact: true, queryKey: brokerageOperationsQueryOptions("all", firstPage).queryKey, }); } else void retryScreen(); }; return { hasPrevious: cursors.length > 0, onNext: () => { if (operations.data?.nextCursor) setPagination({ cursors: [...cursors, operations.data.nextCursor], scope, }); }, onPrevious: () => setPagination({ cursors: cursors.slice(0, -1), scope }), operations, retry, }; } export { useInstrumentOperations };