UNPKG

@saberhq/sail

Version:

Account caching and batched loading for React-based Solana applications.

66 lines 2.17 kB
import { useSolana } from "@saberhq/use-solana"; import { useEffect } from "react"; import { useQuery } from "react-query"; import { fetchKeysMaybe, SailProgramAccountParseError, serializeKeys, useAccountsSubscribe, } from ".."; import { useSail } from "../provider"; export const makeBatchedParsedAccountQuery = (keys, network, fetchKeys, parser, options = {}) => ({ queryKey: [ "sail/batchedParsedAccounts", network, ...(keys ? serializeKeys(keys) : keys === null ? ["null"] : ["undefined"]), ], queryFn: async () => { if (!keys) { return keys; } const accountsData = await fetchKeysMaybe(fetchKeys, keys); return accountsData.map((result) => { 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, }); /** * Parses accounts with the given parser, fetching them in batch. * * @param keys * @param parser * @returns */ export const useBatchedParsedAccounts = (keys, parser, options = {}) => { 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; }; //# sourceMappingURL=useBatchedParsedAccounts.js.map