react-query#useQueries TypeScript Examples

The following examples show how to use react-query#useQueries. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: usePoolAPY.ts    From rari-dApp with GNU Affero General Public License v3.0 6 votes vote down vote up
usePoolsAPY = (pools: PoolInterface[]) => {
  const { rari } = useRari();

  const poolAPYs: UseQueryResult[] = useQueries(
    pools.map(({ type: poolType }) => {
      return {
        queryKey: poolType + " apy",
        queryFn: () => fetchPoolAPY(rari, poolType),
      };
    })
  );

  return useMemo(() => {
    return !poolAPYs.length ? [] : poolAPYs.map(({ data: poolAPY }) => poolAPY);
  }, [poolAPYs]);
}
Example #2
Source File: usePoolBalance.ts    From rari-dApp with GNU Affero General Public License v3.0 6 votes vote down vote up
usePoolBalances = (pools: PoolInterface[]): UseQueryResponse[] => {
  const { rari, address } = useRari();

  // Fetch APYs for all pools
  const poolBalances = useQueries(
    pools.map(({ type: pool }) => {
      return {
        queryKey: address + " " + pool + " balance",
        queryFn: () => fetchPoolBalance({ pool, rari, address }),
      };
    })
  );

  return useMemo(
    () =>
      !poolBalances.length
        ? []
        : poolBalances.map(({ isLoading, error, data }) => ({
            isLoading,
            error,
            data,
          })),
    [poolBalances]
  );
}
Example #3
Source File: useTokenData.ts    From rari-dApp with GNU Affero General Public License v3.0 6 votes vote down vote up
useTokensData = (addresses: string[]) => {
  const tokensData = useQueries(
    addresses.map((address: string) => {
      return {
        queryKey: address + " tokenData",
        queryFn: async () => await fetchTokenData(address),
      };
    })
  );

  return useMemo(() => {
    const ret: any[] = [];

    if (!tokensData.length) return [];

    // Return null altogether
    tokensData.forEach(({ data }) => {
      if (!data) return [];
      ret.push(data);
    });

    if (!ret.length) return [];

    return ret;
  }, [tokensData]);
}
Example #4
Source File: useTokenData.ts    From rari-dApp with GNU Affero General Public License v3.0 6 votes vote down vote up
useTokensDataAsMap = (addresses: string[] = []): TokensDataMap => {
  const tokensData = useQueries(
    addresses.map((address: string) => {
      return {
        queryKey: address + " tokenData",
        queryFn: async () => await fetchTokenData(address),
      };
    })
  );

  return useMemo(() => {
    const ret: TokensDataMap = {};
    if (!tokensData.length) return {};
    tokensData.forEach(({ data }) => {
      const _data = data as TokenData;
      if (_data && _data.address) {
        ret[_data.address] = _data;
      }
    });

    return ret;
  }, [tokensData]);
}
Example #5
Source File: use-get-vault-overview.tsx    From interbtc-ui with Apache License 2.0 6 votes vote down vote up
useGetVaultOverview = ({ address }: { address: string; }): Array<VaultOverview> => {
  // TODO: can we handle this check at the application level rather than in components and utilties?
  // https://www.notion.so/interlay/Handle-api-loaded-check-at-application-level-38fe5d146c8143a88cef2dde7b0e19d8
  const { bridgeLoaded } = useSelector((state: StoreType) => state.general);
  const vaults = useGetVaults({ address });

  // TODO: updating react-query to > 3.28.0 will allow us to type this properly
  const vaultData: Array<any> = useQueries<Array<UseQueryResult<unknown, unknown>>>(
    vaults.map(vault => {
      return {
        queryKey: ['vaultsOverview', address, vault.backingCollateral.currency.ticker],
        queryFn: () => getVaultOverview(vault, newAccountId(window.bridge.api, address)),
        options: {
          enabled: !!bridgeLoaded
        }
      };
    })
  );

  return vaultData.map((data: any) => data.data).filter(data => data !== undefined);
}
Example #6
Source File: use-get-vaults.tsx    From interbtc-ui with Apache License 2.0 6 votes vote down vote up
useGetVaults = ({ address }: { address: string; }): Array<VaultExt<BitcoinUnit>> => {
  // TODO: can we handle this check at the application level rather than in components and utilties?
  // https://www.notion.so/interlay/Handle-api-loaded-check-at-application-level-38fe5d146c8143a88cef2dde7b0e19d8
  const { bridgeLoaded } = useSelector((state: StoreType) => state.general);

  // TODO: updating react-query to > 3.28.0 will allow us to type this properly
  const vaults = useQueries<Array<UseQueryResult<unknown, unknown>>>(
    VAULT_COLLATERAL.map(token => {
      return {
        queryKey: ['vaults', address, token],
        queryFn: () => getVaults(newAccountId(window.bridge.api, address), token),
        options: {
          enabled: !!bridgeLoaded
        }
      };
    })
  );

  return parseVaults(vaults);
}
Example #7
Source File: useToken.ts    From sail with Apache License 2.0 6 votes vote down vote up
useTokens = (mints?: (PublicKey | null | undefined)[]) => {
  const { network } = useSolana();
  const { fetchKeys } = useSail();
  const normalizedMints = useNormalizedMints(mints);
  return useQueries(
    normalizedMints.map((mint) => {
      return makeTokenQuery({
        network,
        address: mint,
        fetchKeys,
      });
    })
  );
}
Example #8
Source File: useFusePoolData.ts    From rari-dApp with GNU Affero General Public License v3.0 5 votes vote down vote up
useFusePoolsData = (poolIds: number[]): FusePoolData[] | null => {
  const { fuse, rari, address } = useRari();

  const poolsData = useQueries(
    poolIds.map((id: number) => {
      return {
        queryKey: id + " apy",
        queryFn: () => {
          return fetchFusePoolData(id.toString(), address, fuse, rari);
        },
      };
    })
  );

  // Get Fuse Pools Data
  const fusePoolsData: FusePoolData[] | null = useMemo(() => {
    // todo - use type FusePoolData
    const ret: any[] = [];

    if (!poolsData.length) return null;

    poolsData.forEach(({ data }, i) => {
      if (!data) return null;
      const _data = data as FusePoolData;
      ret.push({
        ..._data,
        id: poolIds[i],
      });
    });

    if (!ret.length) return null;

    return ret;
  }, [poolsData, poolIds]);

  // Get all the asset arrays for each pool
  const assetsArray: USDPricedFuseAsset[][] | null =
    fusePoolsData?.map((pool) => pool?.assets) ?? null;

  // Construct a hashmap of all the unique assets and their respective tokendata
  const {
    assetsArrayWithTokenData,
  }: {
    assetsArrayWithTokenData: USDPricedFuseAssetWithTokenData[][] | null;
  } = useAssetsMapWithTokenData(assetsArray);

  return useMemo(() => {
    if (assetsArrayWithTokenData && fusePoolsData) {
      return fusePoolsData.map((fusePoolData, i) => ({
        ...fusePoolData,
        assets: assetsArrayWithTokenData[i],
      }));
    }

    return fusePoolsData;
  }, [fusePoolsData, assetsArrayWithTokenData]);
}
Example #9
Source File: useEventsQuery.ts    From backstage with Apache License 2.0 5 votes vote down vote up
useEventsQuery = ({
  selectedCalendars = [],
  calendars = [],
  enabled,
  timeMin,
  timeMax,
  timeZone,
}: Options) => {
  const calendarApi = useApi(gcalendarApiRef);
  const eventQueries = useQueries(
    selectedCalendars
      .filter(id => calendars.find(c => c.id === id))
      .map(calendarId => {
        const calendar = calendars.find(c => c.id === calendarId);

        return {
          queryKey: ['calendarEvents', calendarId, timeMin, timeMax],
          enabled,
          initialData: [],
          refetchInterval: 60000,
          refetchIntervalInBackground: true,
          queryFn: async (): Promise<GCalendarEvent[]> => {
            const data = await calendarApi.getEvents(calendarId, {
              calendarId,
              timeMin,
              timeMax,
              showDeleted: false,
              singleEvents: true,
              maxResults: 100,
              orderBy: 'startTime',
              timeZone,
            });

            return (data.items || []).map(event => {
              const responseStatus = event.attendees?.find(
                a => !!a.self,
              )?.responseStatus;

              return {
                ...event,
                summary: unescape(event.summary || ''),
                calendarId,
                backgroundColor: calendar?.backgroundColor,
                primary: !!calendar?.primary,
                responseStatus,
              };
            });
          },
        };
      }),
  );

  const events = useMemo(
    () => compact(eventQueries.map(({ data }) => data).flat()),
    [eventQueries],
  );

  const isLoading =
    !!eventQueries.find(q => q.isFetching) && events.length === 0;

  return { events, isLoading };
}
Example #10
Source File: useToken.ts    From sail with Apache License 2.0 5 votes vote down vote up
useCertifiedTokens = (mints: (string | null | undefined)[]) => {
  const { network } = useSolana();
  return useQueries(
    mints.map((mint) => makeCertifiedTokenQuery(network, mint))
  );
}
Example #11
Source File: useParsedAccount.ts    From sail with Apache License 2.0 5 votes vote down vote up
useParsedAccounts = <T>(
  keys: (PublicKey | null | undefined)[],
  parser: ProgramAccountParser<T>,
  options: Omit<
    UseQueryOptions<ProgramAccount<T> | null | undefined>,
    "queryFn" | "queryKey"
  > = {}
): ParsedAccountQueryResult<T>[] => {
  const { network } = useSolana();
  const data = useAccountsData(keys);
  return useQueries(
    keys.map(
      (key, i): UseQueryOptions<ProgramAccount<T> | null | undefined> => {
        const datum = data[i];
        return {
          queryKey: [
            "sail/parsedAccount",
            network,
            parser.programID.toString(),
            parser.name,
            key ? key.toString() : key,
          ],
          queryFn: () => {
            if (!datum) {
              return datum;
            }
            try {
              const parsed = parser.parse(datum.accountInfo.data);
              return { publicKey: datum.accountId, account: parsed };
            } catch (e) {
              throw new SailProgramAccountParseError(e, datum, parser);
            }
          },
          enabled: key !== undefined && datum !== undefined,
          ...options,
        };
      }
    )
  );
}
Example #12
Source File: index.tsx    From livepeer-com with MIT License 4 votes vote down vote up
MultistreamTargetsTable = ({
  title = "Multistream Targets",
  stream,
  streamHealth,
  invalidateStream,
  emptyState = defaultEmptyState,
  border = false,
  tableLayout = "fixed",
  ...props
}: {
  title?: string;
  stream: Stream;
  streamHealth?: HealthStatus;
  invalidateStream: (optm?: Stream) => Promise<void>;
  emptyState?: React.ReactNode;
  border?: boolean;
  tableLayout?: string;
}) => {
  const queryClient = useQueryClient();
  const { getMultistreamTarget } = useApi();
  const { state, stateSetter } = useTableState<TargetsTableData>({
    tableId: "multistreamTargetsTable",
  });
  const saveDialogState = useToggleState();
  const errorRecordDialogState = useToggleState();

  const columns = useMemo(
    () => [
      {
        Header: "Name",
        accessor: "name",
        Cell: TextCell,
        sortType: (...params: SortTypeArgs) =>
          stringSort("original.name.children", ...params),
      },
      {
        Header: "Profile",
        accessor: "profile",
        Cell: TextCell,
        sortType: (...params: SortTypeArgs) =>
          stringSort("original.profile.children", ...params),
      },
      {
        Header: "Status",
        accessor: "status",
        Cell: TextCell,
        disableSortBy: true,
      },
      {
        Header: "",
        accessor: "toolbox",
        Cell: TextCell,
        disableSortBy: true,
      },
    ],
    []
  );

  const targetQueryKey = (id: string) => ["multistreamTarget", id];
  const invalidateTargetId = useCallback(
    (id: string) => queryClient.invalidateQueries(targetQueryKey(id)),
    [queryClient]
  );
  const targetRefs = stream.multistream?.targets ?? [];
  const targets = useQueries(
    targetRefs.map((ref) => ({
      queryKey: targetQueryKey(ref.id),
      queryFn: () => getMultistreamTarget(ref.id),
    }))
  ).map((res) => res.data as MultistreamTarget);
  const streamActiveSince = useMemo(() => {
    const activeCondition = streamHealth?.conditions.find(
      (c) => c.type === "Active"
    );
    return activeCondition?.status ? activeCondition.lastTransitionTime : null;
  }, [streamHealth?.conditions]);

  const tableData: TableData<TargetsTableData> = useMemo(() => {
    return {
      isLoading: false,
      data: {
        count: targets.length,
        nextCursor: null,
        rows: targets.map((target, idx) => {
          const ref = targetRefs[idx];
          const status = streamHealth?.multistream?.find(
            (m) => m.target.id === ref.id && m.target.profile === ref.profile
          );
          return {
            id: ref.id,
            name: {
              children: (
                <Tooltip content={ref.id}>
                  <Label>{target?.name ?? "..."}</Label>
                </Tooltip>
              ),
            },
            profile: {
              children: ref.profile + (ref.videoOnly ? " (video-only)" : ""),
            },
            status: {
              children: (
                <TargetStatusBadge
                  stream={stream}
                  target={target}
                  status={status}
                  streamActiveSince={streamActiveSince}
                />
              ),
            },
            toolbox: {
              children: (
                <Toolbox
                  target={target}
                  stream={stream}
                  invalidateTargetId={invalidateTargetId}
                  invalidateStream={invalidateStream}
                />
              ),
            },
          };
        }),
      },
    };
  }, [state.tableId, stream, streamHealth, ...targets]);

  return (
    <Box {...props}>
      <Table
        tableData={tableData}
        state={state}
        stateSetter={stateSetter}
        header={
          <>
            <Heading>{title}</Heading>
          </>
        }
        border={border}
        columns={columns}
        rowSelection={null}
        showOverflow={true}
        noPagination={true}
        emptyState={emptyState}
        tableLayout={tableLayout}
        createAction={{
          onClick: () =>
            stream.isActive
              ? errorRecordDialogState.onOn()
              : saveDialogState.onOn(),
          css: { display: "flex", alignItems: "center", ml: "$1" },
          children: (
            <>
              <PlusIcon />
              <Box as="span" css={{ ml: "$2" }}>
                Create
              </Box>
            </>
          ),
        }}
      />

      <ErrorDialog
        isOpen={errorRecordDialogState.on}
        onOpenChange={errorRecordDialogState.onToggle}
        description="You cannot change multistream preferences while a session is active"
      />

      <SaveTargetDialog
        action={Action.Create}
        isOpen={saveDialogState.on}
        onOpenChange={saveDialogState.onToggle}
        stream={stream}
        invalidate={invalidateStream}
      />
    </Box>
  );
}