@ic-reactor/react 1.0.5 → 1.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +7 -8
  2. package/dist/context/actor.d.ts +64 -0
  3. package/dist/context/actor.js +117 -0
  4. package/dist/context/agent.d.ts +74 -0
  5. package/dist/context/agent.js +128 -0
  6. package/dist/{provider → context}/types.d.ts +2 -1
  7. package/dist/createReactor.d.ts +49 -0
  8. package/dist/createReactor.js +64 -0
  9. package/dist/helpers/authHooks.js +14 -18
  10. package/dist/helpers/extractActorContext.js +0 -82
  11. package/dist/helpers/extractAgentContext.d.ts +1 -1
  12. package/dist/helpers/extractAgentContext.js +3 -81
  13. package/dist/helpers/types.d.ts +15 -15
  14. package/dist/hooks/actor/hooks.d.ts +1 -0
  15. package/dist/hooks/actor/hooks.js +5 -0
  16. package/dist/hooks/actor/index.d.ts +4 -0
  17. package/dist/{provider/types.js → hooks/actor/index.js} +4 -1
  18. package/dist/hooks/actor/useActorState.d.ts +21 -0
  19. package/dist/hooks/actor/useActorState.js +25 -0
  20. package/dist/hooks/actor/useQueryCall.d.ts +28 -0
  21. package/dist/hooks/actor/useQueryCall.js +34 -0
  22. package/dist/hooks/actor/useUpdateCall.d.ts +29 -0
  23. package/dist/hooks/actor/useUpdateCall.js +35 -0
  24. package/dist/hooks/actor/useVisitMethod.d.ts +8 -0
  25. package/dist/hooks/actor/useVisitMethod.js +14 -0
  26. package/dist/hooks/agent/hooks.d.ts +1 -0
  27. package/dist/hooks/agent/hooks.js +5 -0
  28. package/dist/hooks/agent/index.d.ts +6 -0
  29. package/dist/hooks/agent/index.js +22 -0
  30. package/dist/hooks/agent/useAgent.d.ts +14 -0
  31. package/dist/hooks/agent/useAgent.js +18 -0
  32. package/dist/hooks/agent/useAgentManager.d.ts +15 -0
  33. package/dist/hooks/agent/useAgentManager.js +18 -0
  34. package/dist/hooks/agent/useAgentState.d.ts +21 -0
  35. package/dist/hooks/agent/useAgentState.js +25 -0
  36. package/dist/hooks/agent/useAuth.d.ts +57 -0
  37. package/dist/hooks/agent/useAuth.js +61 -0
  38. package/dist/hooks/agent/useAuthState.d.ts +19 -0
  39. package/dist/hooks/agent/useAuthState.js +23 -0
  40. package/dist/hooks/agent/useUserPrincipal.d.ts +17 -0
  41. package/dist/hooks/agent/useUserPrincipal.js +21 -0
  42. package/dist/hooks/index.d.ts +3 -0
  43. package/dist/{provider/hooks → hooks}/index.js +2 -0
  44. package/dist/{provider/hooks → hooks}/types.d.ts +2 -2
  45. package/dist/hooks/types.js +2 -0
  46. package/dist/{provider/hooks → hooks}/useActor.d.ts +6 -4
  47. package/dist/{provider/hooks → hooks}/useActor.js +14 -16
  48. package/dist/index.d.ts +6 -2
  49. package/dist/index.js +6 -2
  50. package/dist/provider/actor.d.ts +18 -56
  51. package/dist/provider/actor.js +19 -107
  52. package/dist/provider/agent.d.ts +20 -62
  53. package/dist/provider/agent.js +21 -113
  54. package/dist/types.d.ts +2 -1
  55. package/dist/types.js +2 -1
  56. package/package.json +3 -3
  57. package/dist/main.d.ts +0 -38
  58. package/dist/main.js +0 -53
  59. package/dist/provider/ActorProvider.d.ts +0 -27
  60. package/dist/provider/ActorProvider.js +0 -30
  61. package/dist/provider/AgentProvider.d.ts +0 -30
  62. package/dist/provider/AgentProvider.js +0 -33
  63. package/dist/provider/hooks/index.d.ts +0 -1
  64. package/dist/provider/index.d.ts +0 -8
  65. package/dist/provider/index.js +0 -25
  66. /package/dist/{provider/hooks → context}/types.js +0 -0
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useAgentState = void 0;
4
+ const hooks_1 = require("./hooks");
5
+ /**
6
+ * Accesses the current state of the agent.
7
+ *
8
+ * @example
9
+ * ```jsx
10
+ * function AgentStateComponent() {
11
+ * const { initialized, initializing } = useAgentState();
12
+ *
13
+ * return (
14
+ * <div>
15
+ * {initialized
16
+ * ? 'Agent is initialized.'
17
+ * : initializing
18
+ * ? 'Agent is initializing...'
19
+ * : 'Agent is not initialized.'}
20
+ * </div>
21
+ * );
22
+ * }
23
+ * ```
24
+ */
25
+ exports.useAgentState = hooks_1.AgentHooks.useAgentState;
@@ -0,0 +1,57 @@
1
+ /**
2
+ * `useAuth` is a custom React hook designed to manage authentication processes in applications interacting with the Internet Computer (IC).
3
+ * It encapsulates the logic for logging in, logging out, and maintaining the authentication state, leveraging an authentication client.
4
+ *
5
+ * @param options - An optional object containing the following properties:
6
+ * - `onAuthentication`: Callback function triggered before authentication starts.
7
+ * - `onAuthenticationSuccess`: Callback function triggered on successful authentication, receives the authenticated `Identity`.
8
+ * - `onAuthenticationFailure`: Callback function triggered on authentication failure, receives the error.
9
+ * - `onLogin`: Callback function triggered before the login process starts.
10
+ * - `onLoginSuccess`: Callback function triggered on successful login, receives the user's `Principal`.
11
+ * - `onLoginError`: Callback function triggered on login error, receives the error.
12
+ * - `onLoggedOut`: Callback function triggered after logging out.
13
+ *
14
+ * @returns An object containing the following properties:
15
+ * - `authenticated`: Boolean indicating if the user is currently authenticated.
16
+ * - `authenticating`: Boolean indicating if an authentication process is currently underway.
17
+ * - `identity`: The authenticated user's `Identity`, if available.
18
+ * - `error`: Any error that occurred during the authentication process.
19
+ * - `login`: Function to initiate the login process, optionally accepting `LoginParameters`.
20
+ * - `logout`: Function to log the user out, optionally accepting `LogoutParameters`.
21
+ * - `authenticate`: Function to authenticate the user, internally used by `login` and `logout`.
22
+ * - `loginLoading`: Boolean indicating if a login operation is in progress.
23
+ * - `loginError`: Error object if an error occurred during the login process.
24
+ *
25
+ * Usage:
26
+ * This hook can be used to add authentication functionality to your IC application components, handling user login, logout, and authentication state management seamlessly.
27
+ *
28
+ * Example:
29
+ * ```jsx
30
+ * const YourComponent = () => {
31
+ * const { login, logout, authenticated, identity, loginError } = useAuth({
32
+ * onLoginSuccess: (principal) => console.log(`Logged in as ${principal}`),
33
+ * onLoginError: (error) => console.error(`Login failed: ${error.message}`),
34
+ * });
35
+ *
36
+ * if (loginError) {
37
+ * return <div>Error logging in: {loginError.message}</div>;
38
+ * }
39
+ *
40
+ * return (
41
+ * <div>
42
+ * {authenticated ? (
43
+ * <>
44
+ * <div>Authenticated as {identity.getPrincipal().toText()}</div>
45
+ * <button onClick={() => logout()}>Logout</button>
46
+ * </>
47
+ * ) : (
48
+ * <button onClick={() => login()}>Login</button>
49
+ * )}
50
+ * </div>
51
+ * );
52
+ * };
53
+ * ```
54
+ *
55
+ * This hook simplifies integrating authentication flows into your IC application, providing hooks for various stages of the authentication process.
56
+ */
57
+ export declare const useAuth: (options?: import("../../types").UseAuthParameters | undefined) => import("../../types").UseAuthReturnType;
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useAuth = void 0;
4
+ const hooks_1 = require("./hooks");
5
+ /**
6
+ * `useAuth` is a custom React hook designed to manage authentication processes in applications interacting with the Internet Computer (IC).
7
+ * It encapsulates the logic for logging in, logging out, and maintaining the authentication state, leveraging an authentication client.
8
+ *
9
+ * @param options - An optional object containing the following properties:
10
+ * - `onAuthentication`: Callback function triggered before authentication starts.
11
+ * - `onAuthenticationSuccess`: Callback function triggered on successful authentication, receives the authenticated `Identity`.
12
+ * - `onAuthenticationFailure`: Callback function triggered on authentication failure, receives the error.
13
+ * - `onLogin`: Callback function triggered before the login process starts.
14
+ * - `onLoginSuccess`: Callback function triggered on successful login, receives the user's `Principal`.
15
+ * - `onLoginError`: Callback function triggered on login error, receives the error.
16
+ * - `onLoggedOut`: Callback function triggered after logging out.
17
+ *
18
+ * @returns An object containing the following properties:
19
+ * - `authenticated`: Boolean indicating if the user is currently authenticated.
20
+ * - `authenticating`: Boolean indicating if an authentication process is currently underway.
21
+ * - `identity`: The authenticated user's `Identity`, if available.
22
+ * - `error`: Any error that occurred during the authentication process.
23
+ * - `login`: Function to initiate the login process, optionally accepting `LoginParameters`.
24
+ * - `logout`: Function to log the user out, optionally accepting `LogoutParameters`.
25
+ * - `authenticate`: Function to authenticate the user, internally used by `login` and `logout`.
26
+ * - `loginLoading`: Boolean indicating if a login operation is in progress.
27
+ * - `loginError`: Error object if an error occurred during the login process.
28
+ *
29
+ * Usage:
30
+ * This hook can be used to add authentication functionality to your IC application components, handling user login, logout, and authentication state management seamlessly.
31
+ *
32
+ * Example:
33
+ * ```jsx
34
+ * const YourComponent = () => {
35
+ * const { login, logout, authenticated, identity, loginError } = useAuth({
36
+ * onLoginSuccess: (principal) => console.log(`Logged in as ${principal}`),
37
+ * onLoginError: (error) => console.error(`Login failed: ${error.message}`),
38
+ * });
39
+ *
40
+ * if (loginError) {
41
+ * return <div>Error logging in: {loginError.message}</div>;
42
+ * }
43
+ *
44
+ * return (
45
+ * <div>
46
+ * {authenticated ? (
47
+ * <>
48
+ * <div>Authenticated as {identity.getPrincipal().toText()}</div>
49
+ * <button onClick={() => logout()}>Logout</button>
50
+ * </>
51
+ * ) : (
52
+ * <button onClick={() => login()}>Login</button>
53
+ * )}
54
+ * </div>
55
+ * );
56
+ * };
57
+ * ```
58
+ *
59
+ * This hook simplifies integrating authentication flows into your IC application, providing hooks for various stages of the authentication process.
60
+ */
61
+ exports.useAuth = hooks_1.AgentHooks.useAuth;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Accesses the current authentication state.
3
+ *
4
+ * @example
5
+ * ```jsx
6
+ * function AuthStateComponent() {
7
+ * const { isAuthenticated, authenticating, identity, error } = useAuthState();
8
+ *
9
+ * return (
10
+ * <div>
11
+ * {authenticating ? 'Authenticating...' : ''}
12
+ * {error ? `Error: ${error.message}` : ''}
13
+ * {isAuthenticated ? `User ${identity?.getPrincipal()} is authenticated.` : 'User is not authenticated.'}
14
+ * </div>
15
+ * );
16
+ * }
17
+ * ```
18
+ */
19
+ export declare const useAuthState: () => import("@ic-reactor/core/dist/types").AuthState;
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useAuthState = void 0;
4
+ const hooks_1 = require("./hooks");
5
+ /**
6
+ * Accesses the current authentication state.
7
+ *
8
+ * @example
9
+ * ```jsx
10
+ * function AuthStateComponent() {
11
+ * const { isAuthenticated, authenticating, identity, error } = useAuthState();
12
+ *
13
+ * return (
14
+ * <div>
15
+ * {authenticating ? 'Authenticating...' : ''}
16
+ * {error ? `Error: ${error.message}` : ''}
17
+ * {isAuthenticated ? `User ${identity?.getPrincipal()} is authenticated.` : 'User is not authenticated.'}
18
+ * </div>
19
+ * );
20
+ * }
21
+ * ```
22
+ */
23
+ exports.useAuthState = hooks_1.AgentHooks.useAuthState;
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Accesses the user's principal.
3
+ *
4
+ * @example
5
+ * ```jsx
6
+ * function UserPrincipalComponent() {
7
+ * const userPrincipal = useUserPrincipal();
8
+ *
9
+ * return (
10
+ * <div>
11
+ * {userPrincipal ? `User principal: ${userPrincipal}` : 'User principal not found.'}
12
+ * </div>
13
+ * );
14
+ * }
15
+ * ```
16
+ */
17
+ export declare const useUserPrincipal: () => import("@dfinity/principal").Principal | undefined;
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useUserPrincipal = void 0;
4
+ const hooks_1 = require("./hooks");
5
+ /**
6
+ * Accesses the user's principal.
7
+ *
8
+ * @example
9
+ * ```jsx
10
+ * function UserPrincipalComponent() {
11
+ * const userPrincipal = useUserPrincipal();
12
+ *
13
+ * return (
14
+ * <div>
15
+ * {userPrincipal ? `User principal: ${userPrincipal}` : 'User principal not found.'}
16
+ * </div>
17
+ * );
18
+ * }
19
+ * ```
20
+ */
21
+ exports.useUserPrincipal = hooks_1.AgentHooks.useUserPrincipal;
@@ -0,0 +1,3 @@
1
+ export * from "./actor";
2
+ export * from "./agent";
3
+ export * from "./useActor";
@@ -14,4 +14,6 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./actor"), exports);
18
+ __exportStar(require("./agent"), exports);
17
19
  __exportStar(require("./useActor"), exports);
@@ -1,7 +1,7 @@
1
1
  /// <reference types="react" />
2
2
  import type { IDL } from "@dfinity/candid";
3
- import { AgentContext } from "../types";
4
- import { ActorHooksReturnType, ActorManagerParameters, BaseActor } from "../../types";
3
+ import { AgentContext } from "../context/types";
4
+ import { ActorHooksReturnType, ActorManagerParameters, BaseActor } from "../types";
5
5
  export interface UseActorParameters extends Omit<ActorManagerParameters, "idlFactory" | "agentManager" | "canisterId"> {
6
6
  canisterId: string;
7
7
  idlFactory?: IDL.InterfaceFactory;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,4 +1,4 @@
1
- import type { BaseActor } from "../../types";
1
+ import type { BaseActor } from "../types";
2
2
  import type { UseActorParameters, UseActorReturn } from "./types";
3
3
  /**
4
4
  * A comprehensive hook that manages both the fetching of Candid interfaces
@@ -22,7 +22,7 @@ import type { UseActorParameters, UseActorReturn } from "./types";
22
22
  *
23
23
  * export const { useQueryCall, useUpdateCall } = extractActorHooks(ActorContext)
24
24
  *
25
- * const LedgerActor = () => {
25
+ * const LedgerActor = ({ children }) => {
26
26
  * const { hooks, fetching, fetchError } = useActor<Ledger>({
27
27
  * canisterId: "ryjl3-tyaaa-aaaaa-aaaba-cai", // ICP Ledger canister
28
28
  * })
@@ -32,7 +32,7 @@ import type { UseActorParameters, UseActorReturn } from "./types";
32
32
  * <h2>IC Canister Interaction</h2>
33
33
  * {fetching && <p>Loading Candid interface...</p>}
34
34
  * {fetchError && <p>Error: {fetchError}</p>}
35
- * {hooks && <CanisterName />}
35
+ * {hooks && children}
36
36
  * </ActorContext.Provider>
37
37
  * )
38
38
  * }
@@ -52,7 +52,9 @@ import type { UseActorParameters, UseActorReturn } from "./types";
52
52
  *
53
53
  * const App = () => (
54
54
  * <AgentProvider withDevtools>
55
- * <LedgerActor />
55
+ * <LedgerActor>
56
+ * <CanisterName />
57
+ * </LedgerActor>
56
58
  * </AgentProvider>
57
59
  * )
58
60
  *
@@ -23,8 +23,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
23
23
  exports.useActor = void 0;
24
24
  const core_1 = require("@ic-reactor/core");
25
25
  const react_1 = require("react");
26
- const __1 = require("..");
27
- const helpers_1 = require("../../helpers");
26
+ const useAgentManager_1 = require("./agent/useAgentManager");
27
+ const helpers_1 = require("../helpers");
28
28
  /**
29
29
  * A comprehensive hook that manages both the fetching of Candid interfaces
30
30
  * and the initialization of actor stores for Internet Computer (IC) canisters.
@@ -47,7 +47,7 @@ const helpers_1 = require("../../helpers");
47
47
  *
48
48
  * export const { useQueryCall, useUpdateCall } = extractActorHooks(ActorContext)
49
49
  *
50
- * const LedgerActor = () => {
50
+ * const LedgerActor = ({ children }) => {
51
51
  * const { hooks, fetching, fetchError } = useActor<Ledger>({
52
52
  * canisterId: "ryjl3-tyaaa-aaaaa-aaaba-cai", // ICP Ledger canister
53
53
  * })
@@ -57,7 +57,7 @@ const helpers_1 = require("../../helpers");
57
57
  * <h2>IC Canister Interaction</h2>
58
58
  * {fetching && <p>Loading Candid interface...</p>}
59
59
  * {fetchError && <p>Error: {fetchError}</p>}
60
- * {hooks && <CanisterName />}
60
+ * {hooks && children}
61
61
  * </ActorContext.Provider>
62
62
  * )
63
63
  * }
@@ -77,7 +77,9 @@ const helpers_1 = require("../../helpers");
77
77
  *
78
78
  * const App = () => (
79
79
  * <AgentProvider withDevtools>
80
- * <LedgerActor />
80
+ * <LedgerActor>
81
+ * <CanisterName />
82
+ * </LedgerActor>
81
83
  * </AgentProvider>
82
84
  * )
83
85
  *
@@ -92,9 +94,9 @@ const useActor = (config) => {
92
94
  fetching: false,
93
95
  fetchError: null,
94
96
  });
95
- const agentManager = (0, __1.useAgentManager)(agentContext);
96
- const fetchCandid = (0, react_1.useCallback)(() => __awaiter(void 0, void 0, void 0, function* () {
97
- if (!canisterId)
97
+ const agentManager = (0, useAgentManager_1.useAgentManager)(agentContext);
98
+ const fetchCandid = (0, react_1.useCallback)((agent) => __awaiter(void 0, void 0, void 0, function* () {
99
+ if (!canisterId || fetching)
98
100
  return;
99
101
  setState({
100
102
  idlFactory: undefined,
@@ -103,7 +105,7 @@ const useActor = (config) => {
103
105
  });
104
106
  try {
105
107
  const candidManager = (0, core_1.createCandidAdapter)({
106
- agentManager,
108
+ agent,
107
109
  didjsCanisterId,
108
110
  });
109
111
  const { idlFactory } = yield candidManager.getCandidDefinition(canisterId);
@@ -123,13 +125,9 @@ const useActor = (config) => {
123
125
  fetching: false,
124
126
  });
125
127
  }
126
- }), [canisterId, didjsCanisterId, agentManager]);
128
+ }), [canisterId, didjsCanisterId]);
127
129
  // Automatically fetch Candid if not already fetched or provided.
128
- (0, react_1.useEffect)(() => {
129
- if (!fetching && !idlFactory) {
130
- fetchCandid();
131
- }
132
- }, [fetchCandid]);
130
+ (0, react_1.useEffect)(() => agentManager.subscribeAgent(fetchCandid, !maybeIdlFactory), [fetchCandid, agentManager]);
133
131
  const hooks = (0, react_1.useMemo)(() => {
134
132
  if (!idlFactory)
135
133
  return null;
@@ -137,7 +135,7 @@ const useActor = (config) => {
137
135
  idlFactory,
138
136
  canisterId }, actorConfig));
139
137
  return (0, helpers_1.actorHooks)(actorManager);
140
- }, [idlFactory]);
138
+ }, [canisterId, idlFactory]);
141
139
  return { hooks, fetching, fetchError };
142
140
  };
143
141
  exports.useActor = useActor;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,9 @@
1
- export * from "./main";
2
- export * from "./provider";
1
+ export * from "./createReactor";
2
+ export * from "./context/actor";
3
+ export * from "./context/agent";
4
+ export * from "./provider/actor";
5
+ export * from "./provider/agent";
6
+ export * from "./hooks";
3
7
  export * as helpers from "./helpers";
4
8
  export * as types from "./types";
5
9
  export * as core from "./core";
package/dist/index.js CHANGED
@@ -27,8 +27,12 @@ var __importStar = (this && this.__importStar) || function (mod) {
27
27
  };
28
28
  Object.defineProperty(exports, "__esModule", { value: true });
29
29
  exports.core = exports.types = exports.helpers = void 0;
30
- __exportStar(require("./main"), exports);
31
- __exportStar(require("./provider"), exports);
30
+ __exportStar(require("./createReactor"), exports);
31
+ __exportStar(require("./context/actor"), exports);
32
+ __exportStar(require("./context/agent"), exports);
33
+ __exportStar(require("./provider/actor"), exports);
34
+ __exportStar(require("./provider/agent"), exports);
35
+ __exportStar(require("./hooks"), exports);
32
36
  exports.helpers = __importStar(require("./helpers"));
33
37
  exports.types = __importStar(require("./types"));
34
38
  exports.core = __importStar(require("./core"));
@@ -1,64 +1,26 @@
1
- import { BaseActor } from "../types";
2
- import { CreateActorContextParameters, CreateActorContextReturnType } from "./types";
1
+ /// <reference types="react" />
3
2
  /**
4
- * Creates a React context specifically designed for managing the state and interactions with an actor on the Internet Computer (IC) blockchain.
5
- * This context facilitates the dynamic creation and management of IC actors within React applications, leveraging the provided configuration options.
3
+ * `ActorProvider` is a React functional component that serves as a context provider for IC actor interactions within a React application.
4
+ * It wraps child components, providing them access to actor-specific hooks and functionalities based on the provided canister ID and configuration.
6
5
  *
7
- * @param reactorParameters A partial configuration object for the actor context, allowing customization and specification of actor-related settings.
8
- * - `canisterId`: The default Canister ID to be used if not overridden in the `ActorProvider` component.
9
- * - Other configurations can include properties related to the actor's interaction, such as agent options or authentication requirements.
6
+ * Props:
7
+ * - `children`: React Node - The child components that will have access to the actor context.
8
+ * - `canisterId` (optional): string - The Canister ID for actor interactions. If not provided, the default from `createActorContext` is used.
9
+ * - `loadingComponent` (optional): React Node - A component displayed during the loading/fetching state. Defaults to a simple message.
10
+ * - `...restConfig`: Additional configuration options that will be merged with the default configuration provided during context creation.
10
11
  *
11
- * @returns An object containing the `ActorProvider` component and various hooks for interacting with the actor.
12
- * - `ActorProvider`: A context provider component that allows child components to access and interact with the configured actor.
13
- * - Hooks: Custom hooks derived from the actor context, facilitating interactions like querying or updating the actor's state.
12
+ * Behavior:
13
+ * - Validates the presence of a `canisterId`. Throws an error if it is missing, ensuring that a valid canister ID is always used for actor operations.
14
+ * - Utilizes `useMemo` to combine the default configuration with the props provided to the `ActorProvider`, optimizing for performance by avoiding unnecessary recalculations.
15
+ * - Employs the `useActor` hook to initiate actor interactions based on the combined configuration, managing states such as `fetching`, `fetchError`, and the actor `hooks`.
16
+ * - Conditionally renders the `loadingComponent` or `fetchError` based on the actor fetching state. Once the actor is ready and no errors are present, it renders the child components, effectively providing them access to the actor context.
14
17
  *
15
18
  * @example
16
19
  * ```jsx
17
- * import React from 'react';
18
- * import { createActorContext } from '@ic-reactor/react';
19
- * import { backend, canisterId, idlFactory } from './declarations/candid'; // Assuming 'declarations/candid' is where your actor interface is defined.
20
- *
21
- * // Initialize the actor context with configuration options
22
- * const { ActorProvider, useActorState, useQueryCall, useUpdateCall } = createActorContext<typeof backend>({
23
- * canisterId,
24
- * idlFactory, // Optional
25
- * });
26
- *
27
- * // A sample component that utilizes the actor context
28
- * const App = () => (
29
- * <AgentProvider>
30
- * <ActorProvider>
31
- * <div>
32
- * <h1>IC Actor Interaction Example</h1>
33
- * <ActorComponent />
34
- * </div>
35
- * </ActorProvider>
36
- * </AgentProvider>
37
- * );
38
- *
39
- * export default App;
40
- *
41
- * // A sample component that uses the actor hooks
42
- * const ActorComponent = () => {
43
- * const { data, loading, error } = useQueryCall({
44
- * functionName: 'backendMethodName',
45
- * args: [],
46
- * refetchInterval: 10000,
47
- * refetchOnMount: true,
48
- * });
49
-
50
- * return (
51
- * <div>
52
- * {loading && <p>Loading...</p>}
53
- * {error && <p>Error: {error.message}</p>}
54
- * {data && <p>Actor data: {data}</p>}
55
- * </div>
56
- * );
57
- * };
20
+ * <ActorProvider canisterId="your-canister-id">
21
+ * <YourComponent />
22
+ * </ActorProvider>
58
23
  * ```
59
- *
60
- * This function streamlines the process of setting up a context for IC actor interactions within a React app, making it easier
61
- * to manage actor state and perform actions such as queries or updates. It abstracts away the complexities involved in directly
62
- * managing IC agents and actors, providing a simple, declarative API for developers.
24
+ * This setup ensures that `YourComponent` and any of its children can interact with the specified IC actor through the context provided by `ActorProvider`.
63
25
  */
64
- export declare function createActorContext<A = BaseActor>(config?: CreateActorContextParameters): CreateActorContextReturnType<A>;
26
+ export declare const ActorProvider: import("react").FC<import("../types").ActorProviderProps>;
@@ -1,117 +1,29 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __rest = (this && this.__rest) || function (s, e) {
26
- var t = {};
27
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
28
- t[p] = s[p];
29
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
30
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
31
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
32
- t[p[i]] = s[p[i]];
33
- }
34
- return t;
35
- };
36
2
  Object.defineProperty(exports, "__esModule", { value: true });
37
- exports.createActorContext = void 0;
38
- const react_1 = __importStar(require("react"));
39
- const useActor_1 = require("./hooks/useActor");
40
- const extractActorContext_1 = require("../helpers/extractActorContext");
3
+ exports.ActorProvider = void 0;
4
+ const hooks_1 = require("../hooks/actor/hooks");
41
5
  /**
42
- * Creates a React context specifically designed for managing the state and interactions with an actor on the Internet Computer (IC) blockchain.
43
- * This context facilitates the dynamic creation and management of IC actors within React applications, leveraging the provided configuration options.
6
+ * `ActorProvider` is a React functional component that serves as a context provider for IC actor interactions within a React application.
7
+ * It wraps child components, providing them access to actor-specific hooks and functionalities based on the provided canister ID and configuration.
44
8
  *
45
- * @param reactorParameters A partial configuration object for the actor context, allowing customization and specification of actor-related settings.
46
- * - `canisterId`: The default Canister ID to be used if not overridden in the `ActorProvider` component.
47
- * - Other configurations can include properties related to the actor's interaction, such as agent options or authentication requirements.
9
+ * Props:
10
+ * - `children`: React Node - The child components that will have access to the actor context.
11
+ * - `canisterId` (optional): string - The Canister ID for actor interactions. If not provided, the default from `createActorContext` is used.
12
+ * - `loadingComponent` (optional): React Node - A component displayed during the loading/fetching state. Defaults to a simple message.
13
+ * - `...restConfig`: Additional configuration options that will be merged with the default configuration provided during context creation.
48
14
  *
49
- * @returns An object containing the `ActorProvider` component and various hooks for interacting with the actor.
50
- * - `ActorProvider`: A context provider component that allows child components to access and interact with the configured actor.
51
- * - Hooks: Custom hooks derived from the actor context, facilitating interactions like querying or updating the actor's state.
15
+ * Behavior:
16
+ * - Validates the presence of a `canisterId`. Throws an error if it is missing, ensuring that a valid canister ID is always used for actor operations.
17
+ * - Utilizes `useMemo` to combine the default configuration with the props provided to the `ActorProvider`, optimizing for performance by avoiding unnecessary recalculations.
18
+ * - Employs the `useActor` hook to initiate actor interactions based on the combined configuration, managing states such as `fetching`, `fetchError`, and the actor `hooks`.
19
+ * - Conditionally renders the `loadingComponent` or `fetchError` based on the actor fetching state. Once the actor is ready and no errors are present, it renders the child components, effectively providing them access to the actor context.
52
20
  *
53
21
  * @example
54
22
  * ```jsx
55
- * import React from 'react';
56
- * import { createActorContext } from '@ic-reactor/react';
57
- * import { backend, canisterId, idlFactory } from './declarations/candid'; // Assuming 'declarations/candid' is where your actor interface is defined.
58
- *
59
- * // Initialize the actor context with configuration options
60
- * const { ActorProvider, useActorState, useQueryCall, useUpdateCall } = createActorContext<typeof backend>({
61
- * canisterId,
62
- * idlFactory, // Optional
63
- * });
64
- *
65
- * // A sample component that utilizes the actor context
66
- * const App = () => (
67
- * <AgentProvider>
68
- * <ActorProvider>
69
- * <div>
70
- * <h1>IC Actor Interaction Example</h1>
71
- * <ActorComponent />
72
- * </div>
73
- * </ActorProvider>
74
- * </AgentProvider>
75
- * );
76
- *
77
- * export default App;
78
- *
79
- * // A sample component that uses the actor hooks
80
- * const ActorComponent = () => {
81
- * const { data, loading, error } = useQueryCall({
82
- * functionName: 'backendMethodName',
83
- * args: [],
84
- * refetchInterval: 10000,
85
- * refetchOnMount: true,
86
- * });
87
-
88
- * return (
89
- * <div>
90
- * {loading && <p>Loading...</p>}
91
- * {error && <p>Error: {error.message}</p>}
92
- * {data && <p>Actor data: {data}</p>}
93
- * </div>
94
- * );
95
- * };
23
+ * <ActorProvider canisterId="your-canister-id">
24
+ * <YourComponent />
25
+ * </ActorProvider>
96
26
  * ```
97
- *
98
- * This function streamlines the process of setting up a context for IC actor interactions within a React app, making it easier
99
- * to manage actor state and perform actions such as queries or updates. It abstracts away the complexities involved in directly
100
- * managing IC agents and actors, providing a simple, declarative API for developers.
27
+ * This setup ensures that `YourComponent` and any of its children can interact with the specified IC actor through the context provided by `ActorProvider`.
101
28
  */
102
- function createActorContext(config = {}) {
103
- const { canisterId: defaultCanisterId } = config, defaultConfig = __rest(config, ["canisterId"]);
104
- const ActorContext = (0, react_1.createContext)(null);
105
- const ActorProvider = (_a) => {
106
- var { children, canisterId = defaultCanisterId, loadingComponent = react_1.default.createElement("div", null, "Fetching canister...") } = _a, restConfig = __rest(_a, ["children", "canisterId", "loadingComponent"]);
107
- if (!canisterId) {
108
- throw new Error("canisterId is required");
109
- }
110
- const config = (0, react_1.useMemo)(() => (Object.assign(Object.assign({}, defaultConfig), restConfig)), [defaultConfig, restConfig]);
111
- const { fetchError, fetching, hooks } = (0, useActor_1.useActor)(Object.assign({ canisterId }, config));
112
- return (react_1.default.createElement(ActorContext.Provider, { value: hooks }, fetching || hooks === null ? fetchError !== null && fetchError !== void 0 ? fetchError : loadingComponent : children));
113
- };
114
- ActorProvider.displayName = "ActorProvider";
115
- return Object.assign({ ActorProvider }, (0, extractActorContext_1.extractActorContext)(ActorContext));
116
- }
117
- exports.createActorContext = createActorContext;
29
+ exports.ActorProvider = hooks_1.ActorHooks.ActorProvider;