import { ChainTypeEnum, CustomerAsset, GetAssetsRequest, PagedResponse } from '@bit-ui-libs/common'; import { UseInfiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query'; import { useInferChainType } from '../../../hooks'; import { useServicesStore } from '../../../stores'; type UseGetTokensOpts = UseInfiniteQueryOptions> & { ownerId: string; queryKey?: string; orgId?: string; isMinted?: boolean; /** * If we want to override the inferred `chainType` * (see `useInferChainType`) */ chainType?: ChainTypeEnum; params?: GetAssetsRequest; }; export function useGetTokens(opts: UseGetTokensOpts) { const { ownerId, queryKey, orgId, isMinted, chainType: overrideChainType, params: otherParams } = opts; const inferredChainType = useInferChainType(); const chainType = overrideChainType ?? inferredChainType; const service = useServicesStore((s) => s.asset[chainType]); const { data: infiniteData, isLoading, isError, refetch, fetchNextPage, hasNextPage, isFetchingNextPage, } = useInfiniteQuery({ queryKey: [queryKey, chainType, ownerId, otherParams], queryFn: async ({ pageParam }) => { const req: GetAssetsRequest = { $page: pageParam, ownerId, isMinted, orgId, ...otherParams }; if (orgId && orgId !== '00000000-0000-0000-0000-000000000000') req.ownerId = undefined; return service.list(req); }, initialPageParam: 1, getNextPageParam: (lastPage) => (lastPage?.page < lastPage?.totalPages ? lastPage?.page + 1 : undefined), staleTime: 0, enabled: !!ownerId, }); const items = infiniteData?.pages?.map((page: PagedResponse) => page.items).flat(); return { items, isLoading, isError, refetch, fetchNextPage, hasNextPage, isFetchingNextPage, }; }