Introduction @ic-reactor/react for React Developers

:rocket: New Example: Using Multiple Actors in a Single Component! :rocket:

I’m thrilled to share a new example I’ve added to ic-reactor that demonstrates a powerful capability: using multiple actors in a single React component. This feature unlocks a world of possibilities for building complex decentralized applications on the Internet Computer blockchain.

In this example, we have a React component called Donation, which integrates two actors seamlessly: the ICP Ledger Canister and the ICDV Donation Canister. Let’s dive into the details:

//...other staff
  const {
    call: refetchBalance,
    data: balance,
    loading: balanceLoading,
  } = useICRC2QueryCall({
    functionName: "icrc1_balance_of",
    args: [{ owner: principal, subaccount: [] }],
  })

  const {
    call: refetchAllowance,
    data: allowance,
    loading: allowanceLoading,
  } = useICRC2QueryCall({
    functionName: "icrc2_allowance",
    args: [
      {
        account: { owner: principal, subaccount: [] },
        spender: {
          owner: icdvCanisterId,
          subaccount: [],
        },
      },
    ],
  })

  const {
    call: mintFromICP,
    loading: mintFromICPLoading,
    data: mintFromICPResult,
    error: mintFromICPError,
  } = useICDVUpdateCall({
    functionName: "mintFromICP",
    onSuccess: () => {
      refetchBalance()
    },
  })

  const {
    call: approve,
    loading: approveLoading,
    data: approveResult,
  } = useICRC2UpdateCall({
    functionName: "icrc2_approve",
    onSuccess: () => {
      refetchAllowance()
      mintFromICP([
        {
          amount: BigInt(amountRef.current?.value || "0"),
          source_subaccount: [],
          target: [],
        },
      ])
    },
  })

// render data and form

How It Works:

  1. Initialization: The Donation component initializes and retrieves the necessary information from both canisters using hooks provided by ic-reactor context api.
  2. Balance and Allowance: It fetches and displays the user’s balance from the ICP Ledger Canister and the allowance granted to the ICDV Donation Canister.
  3. Donation Form: Users can input the amount they want to donate and submit the form.
  4. Transaction Flow: Upon donation submission, the component orchestrates the transaction flow seamlessly. Here’s where the magic of chaining comes into play:
  • When the user initiates a donation, it first triggers the approve function on icp ledger.
  • Upon successful allowance, it automatically calls the mintFromICP function from icdv canister to mints tokens.
  1. Dynamic UI: The UI dynamically updates to reflect the transaction status, providing real-time feedback to the user.

Happy coding! :rocket:

4 Likes