UNPKG

@macalinao/grill

Version:

Modern Solana development kit for React applications with automatic account batching, caching, and transaction notifications

62 lines 2.2 kB
import { fetchAndDecodeAccount } from "@macalinao/gill-extra"; import { useQuery } from "@tanstack/react-query"; import { useMemo } from "react"; import { useGrillContext } from "../contexts/grill-context.js"; import { createAccountQueryKey } from "../query-keys.js"; import { useAccountSubscription } from "./use-account-subscription.js"; /** * Adapts a Decoder to an AccountDecoder for subscriptions. * The decoder needs to be wrapped to handle the EncodedAccount format from subscriptions. */ function createAccountDecoderFromDecoder(decoder) { if (!decoder) { return undefined; } return (encodedAccount) => { const decoded = decoder.decode(encodedAccount.data); return { ...encodedAccount, data: decoded, }; }; } /** * Get the account info for an address. Concurrent queries are batched using a DataLoader. * * @example * ```tsx * // Basic usage - fetch once * const { data: account } = useAccount({ * address: myAddress, * decoder: myDecoder, * }); * * // With subscriptions - auto-update when account changes * const { data: account } = useAccount({ * address: myAddress, * decoder: myDecoder, * subscribeToUpdates: true, * }); * ``` */ export function useAccount({ options, address, decoder, subscribeToUpdates = false, }) { const { accountLoader } = useGrillContext(); // Memoize the account decoder for subscriptions const accountDecoder = useMemo(() => createAccountDecoderFromDecoder(decoder), [decoder]); // Set up subscription if enabled useAccountSubscription(address, accountDecoder, subscribeToUpdates); // TODO(igm): improve the types here and somehow ensure the decoder is the same // for each query of an account return { ...useQuery({ networkMode: "offlineFirst", ...options, // eslint-disable-next-line @tanstack/query/exhaustive-deps queryKey: address ? createAccountQueryKey(address) : [null], queryFn: () => fetchAndDecodeAccount(address, accountLoader, decoder), enabled: !!address, }), address, }; } //# sourceMappingURL=use-account.js.map