use-api-context.ts 932 B

123456789101112131415161718192021222324252627282930
  1. import { useWallet, useConnection } from "@solana/wallet-adapter-react";
  2. import { useMemo } from "react";
  3. import type { Context } from "./api";
  4. import { StateType, useStakeAccount } from "./use-stake-account";
  5. export type { Context } from "./api";
  6. export const useApiContext = (): Context => {
  7. const wallet = useWallet();
  8. const { connection } = useConnection();
  9. const stakeAccount = useStakeAccount();
  10. if (stakeAccount.type !== StateType.Loaded) {
  11. throw new NoStakeAccountSelectedError();
  12. }
  13. return useMemo(
  14. () => ({ wallet, connection, stakeAccount: stakeAccount.account }),
  15. [wallet, connection, stakeAccount],
  16. );
  17. };
  18. class NoStakeAccountSelectedError extends Error {
  19. constructor() {
  20. super(
  21. "The `useApiContext` hook cannot be called before stake accounts have loaded! Ensure all components that use this hook are only rendered if `useStakeAccount` returns a loaded state!",
  22. );
  23. }
  24. }