useFlowTransaction

useFlowTransaction

Hook for executing and managing the lifecycle of a transaction on the Flow blockchain.

Import

import { useFlowTransaction } from '@doodlesteam/flooks';

Usage

const MyComponent = () => {
  const { execute, status, error } = useFlowTransaction({
    code: `
      import NonFungibleToken from 0x...
      import Wearables from 0x...
 
      transaction(recipientAddress: Address, tokenId: UInt64) {
          let collection: &NonFungibleToken.Collection
          let recipient: &{NonFungibleToken.Receiver}
 
          prepare(signer: AuthAccount) {
              self.collection = signer.borrow<&NonFungibleToken.Collection>(from: Wearables.CollectionStoragePath)
                  ?? panic("Could not borrow a reference to the collection")
              self.recipient = getAccount(recipientAddress)
                  .getCapability<&{NonFungibleToken.Receiver}>(Wearables.CollectionPublicPath)
                  .borrow()
                  ?? panic("Could not borrow a reference to the recipient")
          }
 
          execute {
              let token <- self.collection.withdraw(withdrawID: tokenId)
              self.recipient.deposit(token: <-token)
          } 
      }`,
    args: ['0xf8d6e0586b0a20c7', '1000'],
    onTransactionSealed: (result) => {
      console.log('Transaction sealed:', result);
    },
    onTransactionError: (result) => {
      console.error('Transaction error:', result.error);
    },
  });
 
  const handleTransaction = () => {
    execute();
  };
 
  if (status === 'error') return <div>Error: {error?.message}</div>;
 
  return <button onClick={handleTransaction}>Execute Transaction</button>;
};

API Reference

Props

useFlowTransaction accepts a UseFlowTransactionProps object:

  • code: string - The Cadence transaction code to be executed.
  • args: FlowType[] (optional) - Arguments to be passed to the transaction.
  • limit: number (optional) - The computation limit for the transaction.
  • payer, proposer, authorizations: AuthorizationFunction (optional) - Functions for specifying transaction signers. Default to fcl.authz
  • enabled: boolean (optional) - If set to false, disables the transaction.
  • Callbacks for various transaction states like onTransactionPreparing, onTransactionPending, onTransactionSealed, and onTransactionError.

Return Value

The hook returns a UseFlowTransactionResult object, which includes:

  • status: The current status of the transaction (idle, preparing, pending, sealed, error).
  • error: An error object if the transaction failed.
  • execute: A function to initiate the transaction.
  • executeAsync: An async function to initiate the transaction and handle it asynchronously.
  • Additional state indicators like isLoading, isError, isIdle, isSealed, isPreparing, isPending.