react-query#UseQueryOptions TypeScript Examples

The following examples show how to use react-query#UseQueryOptions. 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: graphql.ts    From dope-monorepo with GNU General Public License v3.0 6 votes vote down vote up
useProfileGearQuery = <
      TData = ProfileGearQuery,
      TError = unknown
    >(
      variables?: ProfileGearQueryVariables,
      options?: UseQueryOptions<ProfileGearQuery, TError, TData>
    ) =>
    useQuery<ProfileGearQuery, TError, TData>(
      variables === undefined ? ['ProfileGear'] : ['ProfileGear', variables],
      useFetchData<ProfileGearQuery, ProfileGearQueryVariables>(ProfileGearDocument).bind(null, variables),
      options
    )
Example #2
Source File: useParsedAccount.ts    From sail with Apache License 2.0 6 votes vote down vote up
useParsedAccount = <T>(
  key: PublicKey | null | undefined,
  parser: ProgramAccountParser<T>,
  options: Omit<
    UseQueryOptions<ProgramAccount<T> | null | undefined>,
    "queryFn" | "queryKey"
  > = {}
): ParsedAccountQueryResult<T> => {
  const { fetchKeys, onBatchCache } = useSail();
  const { network } = useSolana();

  const query = useQuery(
    makeParsedAccountQuery(key, network, fetchKeys, parser, options)
  );

  useAccountsSubscribe(useMemo(() => [key], [key]));

  // refresh from the cache whenever the cache is updated
  const { refetch } = query;
  useEffect(() => {
    if (!key) {
      return;
    }
    return onBatchCache((e) => {
      if (e.hasKey(key)) {
        void refetch();
      }
    });
  }, [key, fetchKeys, onBatchCache, refetch]);

  return query;
}
Example #3
Source File: useBatchedParsedAccounts.ts    From sail with Apache License 2.0 6 votes vote down vote up
useBatchedParsedAccounts = <T>(
  keys: BatchedParsedAccountQueryKeys,
  parser: ProgramAccountParser<T>,
  options: Omit<
    UseQueryOptions<BatchedParsedAccountQueryData<T>>,
    "queryFn" | "queryKey"
  > = {}
): BatchParsedAccountQueryResult<T> => {
  const { fetchKeys, onBatchCache } = useSail();
  const { network } = useSolana();

  const query = useQuery(
    makeBatchedParsedAccountQuery(keys, network, fetchKeys, parser, options)
  );

  useAccountsSubscribe(keys);

  // refresh from the cache whenever the cache is updated
  const { refetch } = query;
  useEffect(() => {
    if (!keys) {
      return;
    }
    return onBatchCache((e) => {
      if (keys.find((key) => key && e.hasKey(key))) {
        void refetch();
      }
    });
  }, [keys, fetchKeys, onBatchCache, refetch]);

  return query;
}
Example #4
Source File: useToken.ts    From sail with Apache License 2.0 6 votes vote down vote up
makeTokenQuery = ({
  network,
  address,
  fetchKeys,
}: {
  network: Network;
  address: PublicKey | null | undefined;
  fetchKeys: FetchKeysFn;
}): UseQueryOptions<Token | null | undefined> => ({
  queryKey: ["sail/tokenInfo", network, address?.toString()],
  queryFn: async ({ signal }): Promise<Token | null | undefined> => {
    if (address === null || address === undefined) {
      return address;
    }
    const chainId = networkToChainId(network);
    const info = await fetchNullableWithSessionCache<TokenInfo>(
      makeCertifiedTokenInfoURL(chainId, address.toString()),
      signal
    );
    if (info !== null) {
      return new Token(info);
    }
    const [tokenData] = await fetchKeys([address]);
    if (!tokenData) {
      return null;
    }
    if (!tokenData.data) {
      return tokenData.data;
    }
    const raw = tokenData.data.accountInfo.data;
    const parsed = deserializeMint(raw);
    return Token.fromMint(address, parsed.decimals, {
      chainId: networkToChainId(network),
    });
  },
  // these should never be stale, since token mints are immutable (other than supply)
  staleTime: Infinity,
})
Example #5
Source File: useToken.ts    From sail with Apache License 2.0 6 votes vote down vote up
makeCertifiedTokenQuery = (
  network: Network,
  address: string | null | undefined
): UseQueryOptions<Token | null | undefined> => ({
  queryKey: ["sail/certifiedTokenInfo", network, address],
  queryFn: async ({ signal }): Promise<Token | null | undefined> => {
    if (address === null || address === undefined) {
      return address;
    }
    const chainId = networkToChainId(network);
    const info = await fetchNullableWithSessionCache<TokenInfo>(
      makeCertifiedTokenInfoURL(chainId, address),
      signal
    );
    if (info === null) {
      return null;
    }
    return new Token(info);
  },
  // these should never be stale, since token mints are immutable (other than supply)
  staleTime: Infinity,
})
Example #6
Source File: useDataQuery.ts    From mui-toolpad with MIT License 6 votes vote down vote up
export function useDataQuery(
  dataUrl: string,
  queryId: string | null,
  params: any,
  options: Pick<
    UseQueryOptions<any, unknown, unknown, any[]>,
    'refetchOnWindowFocus' | 'refetchOnReconnect' | 'refetchInterval'
  >,
): UseDataQuery {
  const {
    isLoading,
    isFetching,
    error,
    data: responseData = EMPTY_OBJECT,
    refetch,
  } = useQuery([dataUrl, queryId, params], () => queryId && fetchData(dataUrl, queryId, params), {
    ...options,
    enabled: !!queryId,
  });

  const { data } = responseData;

  const rows = Array.isArray(data) ? data : EMPTY_ARRAY;

  const result: UseDataQuery = React.useMemo(
    () => ({
      isLoading,
      isFetching,
      error,
      data,
      rows,
      refetch,
    }),
    [isLoading, isFetching, error, data, rows, refetch],
  );

  return result;
}
Example #7
Source File: graphql.ts    From dope-monorepo with GNU General Public License v3.0 6 votes vote down vote up
useWalletQuery = <
      TData = WalletQuery,
      TError = unknown
    >(
      variables?: WalletQueryVariables,
      options?: UseQueryOptions<WalletQuery, TError, TData>
    ) =>
    useQuery<WalletQuery, TError, TData>(
      variables === undefined ? ['Wallet'] : ['Wallet', variables],
      useFetchData<WalletQuery, WalletQueryVariables>(WalletDocument).bind(null, variables),
      options
    )
Example #8
Source File: graphql.ts    From dope-monorepo with GNU General Public License v3.0 6 votes vote down vote up
useSearchDopeQuery = <
      TData = SearchDopeQuery,
      TError = unknown
    >(
      variables: SearchDopeQueryVariables,
      options?: UseQueryOptions<SearchDopeQuery, TError, TData>
    ) =>
    useQuery<SearchDopeQuery, TError, TData>(
      ['SearchDope', variables],
      useFetchData<SearchDopeQuery, SearchDopeQueryVariables>(SearchDopeDocument).bind(null, variables),
      options
    )
Example #9
Source File: graphql.ts    From dope-monorepo with GNU General Public License v3.0 6 votes vote down vote up
useRenderDopeQuery = <
      TData = RenderDopeQuery,
      TError = unknown
    >(
      variables?: RenderDopeQueryVariables,
      options?: UseQueryOptions<RenderDopeQuery, TError, TData>
    ) =>
    useQuery<RenderDopeQuery, TError, TData>(
      variables === undefined ? ['RenderDope'] : ['RenderDope', variables],
      useFetchData<RenderDopeQuery, RenderDopeQueryVariables>(RenderDopeDocument).bind(null, variables),
      options
    )
Example #10
Source File: graphql.ts    From dope-monorepo with GNU General Public License v3.0 6 votes vote down vote up
useProfileHustlersQuery = <
      TData = ProfileHustlersQuery,
      TError = unknown
    >(
      variables?: ProfileHustlersQueryVariables,
      options?: UseQueryOptions<ProfileHustlersQuery, TError, TData>
    ) =>
    useQuery<ProfileHustlersQuery, TError, TData>(
      variables === undefined ? ['ProfileHustlers'] : ['ProfileHustlers', variables],
      useFetchData<ProfileHustlersQuery, ProfileHustlersQueryVariables>(ProfileHustlersDocument).bind(null, variables),
      options
    )
Example #11
Source File: graphql.ts    From dope-monorepo with GNU General Public License v3.0 6 votes vote down vote up
useProfileDopesQuery = <
      TData = ProfileDopesQuery,
      TError = unknown
    >(
      variables?: ProfileDopesQueryVariables,
      options?: UseQueryOptions<ProfileDopesQuery, TError, TData>
    ) =>
    useQuery<ProfileDopesQuery, TError, TData>(
      variables === undefined ? ['ProfileDopes'] : ['ProfileDopes', variables],
      useFetchData<ProfileDopesQuery, ProfileDopesQueryVariables>(ProfileDopesDocument).bind(null, variables),
      options
    )
Example #12
Source File: graphql.ts    From dope-monorepo with GNU General Public License v3.0 6 votes vote down vote up
useItemQuery = <
      TData = ItemQuery,
      TError = unknown
    >(
      variables?: ItemQueryVariables,
      options?: UseQueryOptions<ItemQuery, TError, TData>
    ) =>
    useQuery<ItemQuery, TError, TData>(
      variables === undefined ? ['Item'] : ['Item', variables],
      useFetchData<ItemQuery, ItemQueryVariables>(ItemDocument).bind(null, variables),
      options
    )
Example #13
Source File: graphql.ts    From dope-monorepo with GNU General Public License v3.0 6 votes vote down vote up
useHustlerQuery = <
      TData = HustlerQuery,
      TError = unknown
    >(
      variables?: HustlerQueryVariables,
      options?: UseQueryOptions<HustlerQuery, TError, TData>
    ) =>
    useQuery<HustlerQuery, TError, TData>(
      variables === undefined ? ['Hustler'] : ['Hustler', variables],
      useFetchData<HustlerQuery, HustlerQueryVariables>(HustlerDocument).bind(null, variables),
      options
    )
Example #14
Source File: useAnchorQuery.ts    From anchor-web-app with Apache License 2.0 6 votes vote down vote up
useAnchorQuery = <
  TQueryFnData = unknown,
  TError = unknown,
  TData = TQueryFnData,
  TQueryKey extends QueryKey = QueryKey,
>(
  queryKey: TQueryKey,
  queryFn: QueryFunction<TQueryFnData, TQueryKey>,
  options?: Omit<
    UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
    'queryKey' | 'queryFn'
  >,
): UseQueryResult<TData, TError> => {
  const { queryErrorReporter } = useApp();

  return useQuery(queryKey, queryFn, {
    onError: queryErrorReporter,
    ...options,
  });
}
Example #15
Source File: useApi.ts    From kinopub.webos with MIT License 6 votes vote down vote up
function useApi<T extends Method>(
  method: T,
  params: Parameters<ApiClient[T]> = [] as Parameters<ApiClient[T]>,
  options?: UseQueryOptions<Methods[T]>,
) {
  const client = useMemo(() => new ApiClient(), []);
  const query = useQuery<Methods[T]>(
    [method, ...params],
    () =>
      // @ts-expect-error
      client[method](...params) as Methods[T],
    options,
  );

  return query;
}
Example #16
Source File: graphql.ts    From dope-monorepo with GNU General Public License v3.0 6 votes vote down vote up
useDrugQuery = <
      TData = DrugQuery,
      TError = unknown
    >(
      variables?: DrugQueryVariables,
      options?: UseQueryOptions<DrugQuery, TError, TData>
    ) =>
    useQuery<DrugQuery, TError, TData>(
      variables === undefined ? ['Drug'] : ['Drug', variables],
      useFetchData<DrugQuery, DrugQueryVariables>(DrugDocument).bind(null, variables),
      options
    )
Example #17
Source File: graphql.ts    From dope-monorepo with GNU General Public License v3.0 6 votes vote down vote up
useDrugsQuery = <
      TData = DrugsQuery,
      TError = unknown
    >(
      variables?: DrugsQueryVariables,
      options?: UseQueryOptions<DrugsQuery, TError, TData>
    ) =>
    useQuery<DrugsQuery, TError, TData>(
      variables === undefined ? ['Drugs'] : ['Drugs', variables],
      useFetchData<DrugsQuery, DrugsQueryVariables>(DrugsDocument).bind(null, variables),
      options
    )
Example #18
Source File: graphql.ts    From dope-monorepo with GNU General Public License v3.0 6 votes vote down vote up
useAllHustlersQuery = <
      TData = AllHustlersQuery,
      TError = unknown
    >(
      variables?: AllHustlersQueryVariables,
      options?: UseQueryOptions<AllHustlersQuery, TError, TData>
    ) =>
    useQuery<AllHustlersQuery, TError, TData>(
      variables === undefined ? ['AllHustlers'] : ['AllHustlers', variables],
      useFetchData<AllHustlersQuery, AllHustlersQueryVariables>(AllHustlersDocument).bind(null, variables),
      options
    )
Example #19
Source File: graphql.ts    From dope-monorepo with GNU General Public License v3.0 6 votes vote down vote up
useAllItemsQuery = <
      TData = AllItemsQuery,
      TError = unknown
    >(
      variables?: AllItemsQueryVariables,
      options?: UseQueryOptions<AllItemsQuery, TError, TData>
    ) =>
    useQuery<AllItemsQuery, TError, TData>(
      variables === undefined ? ['AllItems'] : ['AllItems', variables],
      useFetchData<AllItemsQuery, AllItemsQueryVariables>(AllItemsDocument).bind(null, variables),
      options
    )
Example #20
Source File: graphql.ts    From dope-monorepo with GNU General Public License v3.0 6 votes vote down vote up
useDopeListingQuery = <
      TData = DopeListingQuery,
      TError = unknown
    >(
      variables?: DopeListingQueryVariables,
      options?: UseQueryOptions<DopeListingQuery, TError, TData>
    ) =>
    useQuery<DopeListingQuery, TError, TData>(
      variables === undefined ? ['DopeListing'] : ['DopeListing', variables],
      useFetchData<DopeListingQuery, DopeListingQueryVariables>(DopeListingDocument).bind(null, variables),
      options
    )
Example #21
Source File: graphql.ts    From dope-monorepo with GNU General Public License v3.0 6 votes vote down vote up
useDopesQuery = <
      TData = DopesQuery,
      TError = unknown
    >(
      variables?: DopesQueryVariables,
      options?: UseQueryOptions<DopesQuery, TError, TData>
    ) =>
    useQuery<DopesQuery, TError, TData>(
      variables === undefined ? ['Dopes'] : ['Dopes', variables],
      useFetchData<DopesQuery, DopesQueryVariables>(DopesDocument).bind(null, variables),
      options
    )
Example #22
Source File: graphql.ts    From dope-monorepo with GNU General Public License v3.0 6 votes vote down vote up
useHustlersWalletQuery = <
      TData = HustlersWalletQuery,
      TError = unknown
    >(
      variables?: HustlersWalletQueryVariables,
      options?: UseQueryOptions<HustlersWalletQuery, TError, TData>
    ) =>
    useQuery<HustlersWalletQuery, TError, TData>(
      variables === undefined ? ['HustlersWallet'] : ['HustlersWallet', variables],
      useFetchData<HustlersWalletQuery, HustlersWalletQueryVariables>(HustlersWalletDocument).bind(null, variables),
      options
    )
Example #23
Source File: person.ts    From frontend with MIT License 5 votes vote down vote up
usePersonList = (options?: UseQueryOptions<PersonResponse[]>) => {
  const { data: session } = useSession()
  return useQuery<PersonResponse[]>(
    endpoints.person.list.url,
    authQueryFnFactory<PersonResponse[]>(session?.accessToken),
    options,
  )
}
Example #24
Source File: useDashboardData.ts    From akashlytics with GNU General Public License v3.0 5 votes vote down vote up
export function useDashboardData<TData = DashboardData>(options?: UseQueryOptions<DashboardData, Error, TData>) {
  return useQuery(queryKeys.dashboardData(), () => getDashboardData(), options)
}
Example #25
Source File: useToken.ts    From sail with Apache License 2.0 5 votes vote down vote up
makeBatchedTokensQuery = ({
  network,
  addresses,
  fetchKeys,
}: {
  network: Network;
  addresses: BatchedParsedAccountQueryKeys;
  fetchKeys: FetchKeysFn;
}): UseQueryOptions<
  readonly (Token | null | undefined)[] | null | undefined
> => ({
  queryKey: [
    "sail/batchedTokens",
    network,
    ...(mapSome(addresses, (a) => a.map((address) => address?.toString())) ?? [
      addresses,
    ]),
  ],
  queryFn: async ({
    signal,
  }): Promise<readonly (Token | null | undefined)[] | null | undefined> => {
    const addressesToFetch: {
      key: PublicKey;
      index: number;
    }[] = [];

    if (!addresses) {
      return addresses;
    }

    const data = await Promise.all(
      addresses.map(async (address, i) => {
        if (address === null || address === undefined) {
          return address;
        }
        const chainId = networkToChainId(network);
        const info = await fetchNullableWithSessionCache<TokenInfo>(
          makeCertifiedTokenInfoURL(chainId, address.toString()),
          signal
        );
        if (info !== null) {
          return new Token(info);
        }
        addressesToFetch.push({ key: address, index: i });
      })
    );

    if (signal?.aborted) {
      throw new Error("Query aborted");
    }

    const tokenDatas = await fetchKeys(addressesToFetch.map((a) => a.key));
    tokenDatas.forEach((tokenData, i) => {
      const index = addressesToFetch[i]?.index;
      if (index === undefined) {
        return;
      }
      if (!tokenData || !tokenData.data) {
        data[index] = null;
        return;
      }
      const raw = tokenData.data.accountInfo.data;
      const parsed = deserializeMint(raw);
      const token = Token.fromMint(tokenData.data.accountId, parsed.decimals, {
        chainId: networkToChainId(network),
      });
      data[index] = token;
    });

    return data;
  },
  // these should never be stale, since token mints are immutable (other than supply)
  staleTime: Infinity,
})
Example #26
Source File: makeProgramParserHooks.ts    From sail with Apache License 2.0 5 votes vote down vote up
makeProgramParserHooks = <M, A extends keyof M>(
  parsers: ProgramAccountParsers<M>
): {
  [K in A]: ProgramParserHooks<M[K]>;
} => {
  const sailParsers = makeProgramAccountParsers<M, A>(parsers);
  const hooks = mapValues(
    sailParsers,
    <T extends M[A]>(
      parser: ProgramAccountParser<T>
    ): ProgramParserHooks<T> => ({
      useSingleData: (
        key: PublicKey | null | undefined,
        options?: Omit<
          UseQueryOptions<ProgramAccount<T> | null | undefined>,
          "queryFn" | "queryKey"
        >
      ): ParsedAccountQueryResult<T> => useParsedAccount(key, parser, options),
      useData: (
        keys: (PublicKey | null | undefined)[],
        options?: Omit<
          UseQueryOptions<ProgramAccount<T> | null | undefined>,
          "queryFn" | "queryKey"
        >
      ): ParsedAccountQueryResult<T>[] =>
        useParsedAccounts<T>(keys, parser, options),
      useBatchedData: (
        keys: BatchedParsedAccountQueryKeys,
        options?: Omit<
          UseQueryOptions<BatchedParsedAccountQueryData<T>>,
          "queryFn" | "queryKey"
        >
      ): BatchParsedAccountQueryResult<T> =>
        useBatchedParsedAccounts<T>(keys, parser, options),
    })
  );
  return hooks as unknown as {
    [K in A]: ProgramParserHooks<M[K]>;
  };
}
Example #27
Source File: useBatchedParsedAccounts.ts    From sail with Apache License 2.0 5 votes vote down vote up
makeBatchedParsedAccountQuery = <T>(
  keys: BatchedParsedAccountQueryKeys,
  network: Network,
  fetchKeys: FetchKeysFn,
  parser: ProgramAccountParser<T>,
  options: Omit<
    UseQueryOptions<BatchedParsedAccountQueryData<T>>,
    "queryFn" | "queryKey"
  > = {}
): UseQueryOptions<BatchedParsedAccountQueryData<T>> => ({
  queryKey: [
    "sail/batchedParsedAccounts",
    network,
    ...(keys ? serializeKeys(keys) : keys === null ? ["null"] : ["undefined"]),
  ],
  queryFn: async (): Promise<BatchedParsedAccountQueryData<T>> => {
    if (!keys) {
      return keys;
    }
    const accountsData = await fetchKeysMaybe(fetchKeys, keys);
    return accountsData.map((result): ProgramAccount<T> | null | undefined => {
      if (!result) {
        return result;
      }
      const data = result.data;
      if (!data) {
        return null;
      }

      try {
        const parsed = parser.parse(data.accountInfo.data);
        return {
          publicKey: data.accountId,
          account: parsed,
        };
      } catch (e) {
        throw new SailProgramAccountParseError(e, data, parser);
      }
    });
  },
  staleTime: Infinity,
  ...options,
})
Example #28
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 #29
Source File: useParsedAccount.ts    From sail with Apache License 2.0 5 votes vote down vote up
makeParsedAccountQuery = <T>(
  key: PublicKey | null | undefined,
  network: Network,
  fetchKeys: FetchKeysFn,
  parser: ProgramAccountParser<T>,
  options: Omit<
    UseQueryOptions<ProgramAccount<T> | null | undefined>,
    "queryFn" | "queryKey"
  > = {}
): UseQueryOptions<ProgramAccount<T> | null | undefined> => ({
  queryKey: [
    "sail/parsedAccount",
    network,
    parser.programID.toString(),
    parser.name,
    key ? key.toString() : key,
  ],
  queryFn: async (): Promise<ProgramAccount<T> | null | undefined> => {
    const [result] = await fetchKeysMaybe(fetchKeys, [key]);
    if (!result) {
      return result;
    }
    const data = result.data;
    if (!data) {
      return null;
    }

    try {
      const parsed = parser.parse(data.accountInfo.data);
      return {
        publicKey: data.accountId,
        account: parsed,
      };
    } catch (e) {
      throw new SailProgramAccountParseError(e, data, parser);
    }
  },
  staleTime: Infinity,
  enabled: key !== undefined,
  ...options,
})