import { AgentProvider, extractActorHooks, useActor } from "@ic-reactor/react"
import { createContext } from "react"
import type { ActorHooks } from "@ic-reactor/react/dist/types"
// With this import, you can have type safety for the actor's interface.
// You can get it from the `.did.d.ts` file generated by the DFX tool.
// or from dashboard https://dashboard.internetcomputer.org/canisters/<canister-id>
import type { Ledger } from "../declarations/ledger"
const ActorContext = createContext<ActorHooks<Ledger> | null>(null)
export const { useQueryCall, useUpdateCall } = extractActorHooks(ActorContext)
const LedgerActor = ({ children }) => {
const { hooks, fetching, fetchError } = useActor<Ledger>({
canisterId: "ryjl3-tyaaa-aaaaa-aaaba-cai", // ICP Ledger canister
idlFactory // optional: it will be fetched using CandidAdapter
})
return (
<ActorContext.Provider value={hooks}>
<h2>IC Canister Interaction</h2>
{fetching && <p>Loading Candid interface...</p>}
{fetchError && <p>Error: {fetchError}</p>}
{hooks && children}
</ActorContext.Provider>
)
}
// later in the code
const CanisterName = () => {
const { data } = useQueryCall({
functionName: "name",
})
return (
<div>
<h3>Query Call</h3>
<p>Result: {JSON.stringify(data)}</p>
</div>
)
}
const App = () => (
<AgentProvider withDevtools>
<CandidAdapterProvider>
<LedgerActor>
<CanisterName />
</LedgerActor>
</CandidAdapterProvider>
</AgentProvider>
)
export default App
A comprehensive hook that manages both the fetching of Candid interfaces and the initialization of actor stores for Internet Computer (IC) canisters. It simplifies the process of interacting with canisters by encapsulating the logic for Candid retrieval and actor store management.
You can use react context to share the actor hooks across your application.