@ic-reactor/react 1.0.4 → 1.0.5

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 (57) hide show
  1. package/README.md +8 -17
  2. package/dist/helpers/{actor.d.ts → actorHooks.d.ts} +4 -7
  3. package/dist/helpers/{actor.js → actorHooks.js} +8 -15
  4. package/dist/helpers/agentHooks.d.ts +3 -0
  5. package/dist/helpers/{agent.js → agentHooks.js} +3 -3
  6. package/dist/helpers/authHooks.d.ts +2 -0
  7. package/dist/helpers/authHooks.js +127 -0
  8. package/dist/helpers/extractActorContext.d.ts +3 -0
  9. package/dist/{provider/actor/context.js → helpers/extractActorContext.js} +14 -65
  10. package/dist/helpers/extractAgentContext.d.ts +27 -0
  11. package/dist/helpers/extractAgentContext.js +134 -0
  12. package/dist/helpers/index.d.ts +5 -3
  13. package/dist/helpers/index.js +5 -3
  14. package/dist/helpers/types.d.ts +20 -30
  15. package/dist/index.d.ts +0 -1
  16. package/dist/index.js +0 -1
  17. package/dist/main.d.ts +38 -2
  18. package/dist/main.js +39 -21
  19. package/dist/provider/ActorProvider.d.ts +27 -0
  20. package/dist/provider/ActorProvider.js +30 -0
  21. package/dist/provider/AgentProvider.d.ts +30 -0
  22. package/dist/provider/AgentProvider.js +33 -0
  23. package/dist/provider/actor.d.ts +64 -0
  24. package/dist/provider/actor.js +117 -0
  25. package/dist/provider/agent.d.ts +71 -0
  26. package/dist/provider/agent.js +124 -0
  27. package/dist/provider/hooks/index.d.ts +1 -0
  28. package/dist/{hooks → provider/hooks}/index.js +1 -1
  29. package/dist/provider/hooks/types.d.ts +15 -0
  30. package/dist/provider/hooks/useActor.d.ts +63 -0
  31. package/dist/{hooks/useReactor.js → provider/hooks/useActor.js} +51 -29
  32. package/dist/provider/index.d.ts +8 -2
  33. package/dist/provider/index.js +9 -2
  34. package/dist/provider/types.d.ts +27 -0
  35. package/dist/provider/{agent/index.js → types.js} +1 -2
  36. package/dist/types.d.ts +8 -8
  37. package/dist/types.js +2 -4
  38. package/package.json +3 -3
  39. package/dist/helpers/agent.d.ts +0 -3
  40. package/dist/helpers/auth.d.ts +0 -3
  41. package/dist/helpers/auth.js +0 -108
  42. package/dist/hooks/index.d.ts +0 -1
  43. package/dist/hooks/types.d.ts +0 -19
  44. package/dist/hooks/useReactor.d.ts +0 -41
  45. package/dist/provider/actor/context.d.ts +0 -20
  46. package/dist/provider/actor/index.d.ts +0 -3
  47. package/dist/provider/actor/index.js +0 -9
  48. package/dist/provider/actor/types.d.ts +0 -21
  49. package/dist/provider/actor/types.js +0 -2
  50. package/dist/provider/agent/context.d.ts +0 -7
  51. package/dist/provider/agent/context.js +0 -56
  52. package/dist/provider/agent/hooks.d.ts +0 -12
  53. package/dist/provider/agent/hooks.js +0 -43
  54. package/dist/provider/agent/index.d.ts +0 -2
  55. package/dist/provider/agent/types.d.ts +0 -12
  56. package/dist/provider/agent/types.js +0 -2
  57. /package/dist/{hooks → provider/hooks}/types.js +0 -0
package/README.md CHANGED
@@ -3,6 +3,7 @@
3
3
  ## Features
4
4
 
5
5
  - **React Hooks Integration**: Custom hooks for managing blockchain actor states and authentication within React applications.
6
+ - **Type-Safe Actor Interactions**: Type-safe interaction with IC actors using the provided actor declaration file.
6
7
  - **Efficient State Management**: Utilize the power of Zustand for global state management in React components.
7
8
  - **Asynchronous Data Handling**: Easy handling of asynchronous operations related to IC actors.
8
9
  - **Authentication Support**: Integrated hooks for managing authentication with the IC blockchain.
@@ -29,7 +30,7 @@ Here's a simple example to get you started:
29
30
  First, create an actor declaration file:
30
31
 
31
32
  ```ts
32
- // store.ts
33
+ // actor.ts
33
34
  import { canisterId, idlFactory, actor } from "declaration/actor"
34
35
  import { createReactor } from "@ic-reactor/react"
35
36
 
@@ -37,7 +38,7 @@ type Actor = typeof actor
37
38
 
38
39
  export const { useActorStore, useAuthClient, useQueryCall } =
39
40
  createReactor<Actor>({
40
- canisterId: "rrkah-fqaaa-aaaaa-aaaaq-cai",
41
+ canisterId,
41
42
  idlFactory,
42
43
  host: "https://localhost:4943",
43
44
  })
@@ -47,7 +48,7 @@ Then, use the `useQueryCall` hook to call your canister method:
47
48
 
48
49
  ```jsx
49
50
  // Balance.tsx
50
- import { useQueryCall } from "./store"
51
+ import { useQueryCall } from "./actor"
51
52
 
52
53
  const Balance = ({ principal }) => {
53
54
  const { call, data, loading, error } = useQueryCall({
@@ -62,7 +63,7 @@ const Balance = ({ principal }) => {
62
63
 
63
64
  return (
64
65
  <div>
65
- <button onClick={() => call()} disabled={loading}>
66
+ <button onClick={call} disabled={loading}>
66
67
  {loading ? "Loading..." : "Refresh"}
67
68
  </button>
68
69
  {loading && <p>Loading...</p>}
@@ -81,7 +82,7 @@ export default Balance
81
82
 
82
83
  ```jsx
83
84
  // Login.tsx
84
- import { useAuthClient } from "./store"
85
+ import { useAuthClient } from "./actor"
85
86
 
86
87
  const Login = () => {
87
88
  const {
@@ -104,21 +105,11 @@ const Login = () => {
104
105
  </div>
105
106
  {authenticated ? (
106
107
  <div>
107
- <button onClick={() => logout()}>Logout</button>
108
+ <button onClick={logout}>Logout</button>
108
109
  </div>
109
110
  ) : (
110
111
  <div>
111
- <button
112
- onClick={() =>
113
- login({
114
- identityProvider:
115
- process.env.DFX_NETWORK === "ic"
116
- ? "https://identity.ic0.app/#authorize"
117
- : "http://rdmx6-jaaaa-aaaaa-aaadq-cai.localhost:4943/#authorize",
118
- })
119
- }
120
- disabled={authenticating}
121
- >
112
+ <button onClick={login} disabled={authenticating}>
122
113
  Login
123
114
  </button>
124
115
  </div>
@@ -1,6 +1,5 @@
1
- import type { ActorHooks } from "../types";
2
- import type { BaseActor } from "@ic-reactor/core/dist/types";
3
- import { ActorManager } from "@ic-reactor/core";
1
+ import type { ActorHooksReturnType } from "../types";
2
+ import type { ActorManager, BaseActor } from "@ic-reactor/core/dist/types";
4
3
  /**
5
4
  * Provides a set of React hooks designed for interacting with actors in an Internet Computer (IC) project using the React framework and Zustand for state management.
6
5
  *
@@ -11,11 +10,9 @@ import { ActorManager } from "@ic-reactor/core";
11
10
  * - initialize: Function to initialize actor management.
12
11
  * - useActorState: Hook for accessing the actor's state including the canister ID.
13
12
  * - useVisitMethod: Hook for memoizing a method visit service for a given actor method name.
14
- * - useReactorCall: Hook for making calls to actor methods with support for loading states, errors, and custom event handlers.
15
13
  * - useQueryCall: Hook specifically designed for query calls to actors with features such as automatic refetching on mount and at specified intervals.
16
- * - useUpdateCall: Alias for useReactorCall, tailored for update calls to actors.
17
- * - useMethodCall: Combines useVisitMethod and useReactorCall for a streamlined experience when calling actor methods, including visitation and state management.
14
+ * - useUpdateCall: Hook specifically designed for update calls to actors with features such as error handling and loading state management.
18
15
  *
19
16
  * Each hook is designed to simplify the process of interacting with actors in IC projects by abstracting away the complexity of state management, error handling, and method invocation.
20
17
  */
21
- export declare const getActorHooks: <A = BaseActor>(actorManager: ActorManager<A>) => ActorHooks<A>;
18
+ export declare const actorHooks: <A = BaseActor>(actorManager: ActorManager<A>) => ActorHooksReturnType<A>;
@@ -20,7 +20,7 @@ var __rest = (this && this.__rest) || function (s, e) {
20
20
  return t;
21
21
  };
22
22
  Object.defineProperty(exports, "__esModule", { value: true });
23
- exports.getActorHooks = void 0;
23
+ exports.actorHooks = void 0;
24
24
  const react_1 = require("react");
25
25
  const zustand_1 = require("zustand");
26
26
  const DEFAULT_STATE = {
@@ -38,26 +38,24 @@ const DEFAULT_STATE = {
38
38
  * - initialize: Function to initialize actor management.
39
39
  * - useActorState: Hook for accessing the actor's state including the canister ID.
40
40
  * - useVisitMethod: Hook for memoizing a method visit service for a given actor method name.
41
- * - useReactorCall: Hook for making calls to actor methods with support for loading states, errors, and custom event handlers.
42
41
  * - useQueryCall: Hook specifically designed for query calls to actors with features such as automatic refetching on mount and at specified intervals.
43
- * - useUpdateCall: Alias for useReactorCall, tailored for update calls to actors.
44
- * - useMethodCall: Combines useVisitMethod and useReactorCall for a streamlined experience when calling actor methods, including visitation and state management.
42
+ * - useUpdateCall: Hook specifically designed for update calls to actors with features such as error handling and loading state management.
45
43
  *
46
44
  * Each hook is designed to simplify the process of interacting with actors in IC projects by abstracting away the complexity of state management, error handling, and method invocation.
47
45
  */
48
- const getActorHooks = (actorManager) => {
46
+ const actorHooks = (actorManager) => {
49
47
  const { actorStore, canisterId, visitFunction, callMethod, initialize } = actorManager;
50
48
  const useActorState = () => (Object.assign(Object.assign({}, (0, zustand_1.useStore)(actorStore)), { canisterId }));
51
49
  const useVisitMethod = (functionName) => {
52
50
  return (0, react_1.useMemo)(() => visitFunction[functionName], [functionName]);
53
51
  };
54
- const useReactorCall = (_a) => {
52
+ const useMethodCall = (_a) => {
55
53
  var { args = [], functionName, throwOnError = false } = _a, events = __rest(_a, ["args", "functionName", "throwOnError"]);
56
54
  const [state, setState] = (0, react_1.useState)(DEFAULT_STATE);
57
55
  const reset = (0, react_1.useCallback)(() => setState(DEFAULT_STATE), []);
58
56
  const call = (0, react_1.useCallback)((eventOrReplaceArgs) => __awaiter(void 0, void 0, void 0, function* () {
59
57
  var _b, _c, _d, _e, _f;
60
- setState({ data: undefined, error: undefined, loading: true });
58
+ setState((prev) => (Object.assign(Object.assign({}, prev), { error: undefined, loading: true })));
61
59
  (_b = events === null || events === void 0 ? void 0 : events.onLoading) === null || _b === void 0 ? void 0 : _b.call(events, true);
62
60
  try {
63
61
  const replaceArgs = eventOrReplaceArgs instanceof Array ? eventOrReplaceArgs : args;
@@ -81,7 +79,7 @@ const getActorHooks = (actorManager) => {
81
79
  };
82
80
  const useQueryCall = (_a) => {
83
81
  var { refetchOnMount = true, refetchInterval = false } = _a, rest = __rest(_a, ["refetchOnMount", "refetchInterval"]);
84
- const _b = useReactorCall(rest), { call } = _b, state = __rest(_b, ["call"]);
82
+ const _b = useMethodCall(rest), { call } = _b, state = __rest(_b, ["call"]);
85
83
  const intervalId = (0, react_1.useRef)();
86
84
  (0, react_1.useEffect)(() => {
87
85
  if (refetchInterval) {
@@ -94,18 +92,13 @@ const getActorHooks = (actorManager) => {
94
92
  }, [refetchInterval, refetchOnMount]);
95
93
  return Object.assign({ call }, state);
96
94
  };
97
- const useUpdateCall = useReactorCall;
98
- const useMethodCall = (args) => {
99
- const visit = useVisitMethod(args.functionName);
100
- return Object.assign({ visit }, useReactorCall(args));
101
- };
95
+ const useUpdateCall = useMethodCall;
102
96
  return {
103
97
  initialize,
104
98
  useQueryCall,
105
99
  useUpdateCall,
106
100
  useActorState,
107
- useMethodCall,
108
101
  useVisitMethod,
109
102
  };
110
103
  };
111
- exports.getActorHooks = getActorHooks;
104
+ exports.actorHooks = actorHooks;
@@ -0,0 +1,3 @@
1
+ import type { AgentManager } from "@ic-reactor/core/dist/types";
2
+ import type { AgentHooksReturnType } from "./types";
3
+ export declare const agentHooks: (agentManager: AgentManager) => AgentHooksReturnType;
@@ -1,9 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getAgentHooks = void 0;
3
+ exports.agentHooks = void 0;
4
4
  const react_1 = require("react");
5
5
  const zustand_1 = require("zustand");
6
- const getAgentHooks = (agentManager) => {
6
+ const agentHooks = (agentManager) => {
7
7
  const { agentStore, getAgent, subscribeAgent } = agentManager;
8
8
  const useAgentState = () => (0, zustand_1.useStore)(agentStore);
9
9
  const useAgent = () => {
@@ -16,4 +16,4 @@ const getAgentHooks = (agentManager) => {
16
16
  useAgentState,
17
17
  };
18
18
  };
19
- exports.getAgentHooks = getAgentHooks;
19
+ exports.agentHooks = agentHooks;
@@ -0,0 +1,2 @@
1
+ import type { AgentManager, AuthHooksReturnType } from "../types";
2
+ export declare const authHooks: (agentManager: AgentManager) => AuthHooksReturnType;
@@ -0,0 +1,127 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.authHooks = void 0;
13
+ const zustand_1 = require("zustand");
14
+ const react_1 = require("react");
15
+ const tools_1 = require("@ic-reactor/core/dist/tools");
16
+ const authHooks = (agentManager) => {
17
+ const { authenticate: authenticator, authStore, isLocalEnv } = agentManager;
18
+ const useAuthState = () => (0, zustand_1.useStore)(authStore);
19
+ const useUserPrincipal = () => { var _a, _b; return (_b = (_a = useAuthState()) === null || _a === void 0 ? void 0 : _a.identity) === null || _b === void 0 ? void 0 : _b.getPrincipal(); };
20
+ const useAuthClient = ({ onAuthentication, onAuthenticationSuccess, onAuthenticationFailure, onLogin, onLoginSuccess, onLoginError, onLoggedOut, } = {}) => {
21
+ const [loginState, setLoginState] = (0, react_1.useState)({
22
+ loading: false,
23
+ error: null,
24
+ });
25
+ const { authClient, authenticated, authenticating, error, identity } = useAuthState();
26
+ const authenticate = (0, react_1.useCallback)(() => __awaiter(void 0, void 0, void 0, function* () {
27
+ const authenticatePromise = new Promise((resolve, reject) => {
28
+ authenticator()
29
+ .then((identity) => {
30
+ onAuthenticationSuccess === null || onAuthenticationSuccess === void 0 ? void 0 : onAuthenticationSuccess(identity);
31
+ resolve(identity);
32
+ })
33
+ .catch((e) => {
34
+ onAuthenticationFailure === null || onAuthenticationFailure === void 0 ? void 0 : onAuthenticationFailure(e);
35
+ reject(e);
36
+ });
37
+ });
38
+ onAuthentication === null || onAuthentication === void 0 ? void 0 : onAuthentication(() => authenticatePromise);
39
+ return authenticatePromise;
40
+ }), [
41
+ authenticator,
42
+ onAuthentication,
43
+ onAuthenticationSuccess,
44
+ onAuthenticationFailure,
45
+ ]);
46
+ const login = (0, react_1.useCallback)((options) => __awaiter(void 0, void 0, void 0, function* () {
47
+ setLoginState({ loading: true, error: null });
48
+ const loginPromise = new Promise((resolve, reject) => {
49
+ try {
50
+ if (!authClient) {
51
+ throw new Error("Auth client not initialized");
52
+ }
53
+ authClient.login(Object.assign(Object.assign({ identityProvider: isLocalEnv
54
+ ? tools_1.IC_INTERNET_IDENTITY_PROVIDER
55
+ : tools_1.LOCAL_INTERNET_IDENTITY_PROVIDER }, options), { onSuccess: () => {
56
+ authenticate()
57
+ .then((identity) => {
58
+ var _a;
59
+ const principal = identity.getPrincipal();
60
+ (_a = options === null || options === void 0 ? void 0 : options.onSuccess) === null || _a === void 0 ? void 0 : _a.call(options);
61
+ onLoginSuccess === null || onLoginSuccess === void 0 ? void 0 : onLoginSuccess(principal);
62
+ resolve(principal);
63
+ })
64
+ .catch((e) => {
65
+ const error = e;
66
+ setLoginState({ loading: false, error });
67
+ onLoginError === null || onLoginError === void 0 ? void 0 : onLoginError(error);
68
+ reject(error);
69
+ });
70
+ }, onError: (e) => {
71
+ var _a;
72
+ (_a = options === null || options === void 0 ? void 0 : options.onError) === null || _a === void 0 ? void 0 : _a.call(options, e);
73
+ const error = new Error("Login failed: " + e);
74
+ setLoginState({ loading: false, error });
75
+ onLoginError === null || onLoginError === void 0 ? void 0 : onLoginError(error);
76
+ reject(error);
77
+ } }));
78
+ }
79
+ catch (e) {
80
+ const error = e;
81
+ setLoginState({ loading: false, error });
82
+ onLoginError === null || onLoginError === void 0 ? void 0 : onLoginError(error);
83
+ reject(error);
84
+ }
85
+ });
86
+ onLogin === null || onLogin === void 0 ? void 0 : onLogin(() => loginPromise);
87
+ }), [
88
+ authClient,
89
+ onLogin,
90
+ onLoginSuccess,
91
+ onLoginError,
92
+ isLocalEnv,
93
+ authenticate,
94
+ ]);
95
+ const logout = (0, react_1.useCallback)((options) => __awaiter(void 0, void 0, void 0, function* () {
96
+ if (!authClient) {
97
+ throw new Error("Auth client not initialized");
98
+ }
99
+ yield authClient.logout(options);
100
+ yield authenticate();
101
+ onLoggedOut === null || onLoggedOut === void 0 ? void 0 : onLoggedOut();
102
+ }), [authClient, onLoggedOut]);
103
+ (0, react_1.useEffect)(() => {
104
+ if (!authClient && !authenticating) {
105
+ authenticate();
106
+ }
107
+ }, [authClient, authenticating]);
108
+ return {
109
+ authClient,
110
+ authenticated,
111
+ authenticating,
112
+ identity,
113
+ error,
114
+ login,
115
+ logout,
116
+ authenticate,
117
+ loginLoading: loginState.loading,
118
+ loginError: loginState.error,
119
+ };
120
+ };
121
+ return {
122
+ useUserPrincipal,
123
+ useAuthState,
124
+ useAuthClient,
125
+ };
126
+ };
127
+ exports.authHooks = authHooks;
@@ -0,0 +1,3 @@
1
+ /// <reference types="react" />
2
+ import type { ActorHooksReturnType, BaseActor, CreateActorContextReturnType } from "../types";
3
+ export declare function extractActorContext<A = BaseActor>(actorContext: React.Context<ActorHooksReturnType<A> | null>): Omit<CreateActorContextReturnType<A>, "ActorProvider">;
@@ -1,59 +1,8 @@
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.extractActorHooks = exports.createReactorContext = void 0;
38
- const react_1 = __importStar(require("react"));
39
- const useReactor_1 = require("../../hooks/useReactor");
40
- function createReactorContext(_a = {}) {
41
- var { canisterId: defaultCanisterId } = _a, defaultConfig = __rest(_a, ["canisterId"]);
42
- const ActorContext = (0, react_1.createContext)(null);
43
- const ActorProvider = (_a) => {
44
- var { children, canisterId = defaultCanisterId, loadingComponent = react_1.default.createElement("div", null, "Fetching canister...") } = _a, restConfig = __rest(_a, ["children", "canisterId", "loadingComponent"]);
45
- if (!canisterId) {
46
- throw new Error("canisterId is required");
47
- }
48
- const config = (0, react_1.useMemo)(() => (Object.assign(Object.assign({}, defaultConfig), restConfig)), [defaultConfig, restConfig]);
49
- const { fetchError, fetching, hooks } = (0, useReactor_1.useReactor)(Object.assign({ canisterId }, config));
50
- return (react_1.default.createElement(ActorContext.Provider, { value: hooks }, fetching || hooks === null ? fetchError !== null && fetchError !== void 0 ? fetchError : loadingComponent : children));
51
- };
52
- ActorProvider.displayName = "ActorProvider";
53
- return Object.assign({ ActorProvider }, extractActorHooks(ActorContext));
54
- }
55
- exports.createReactorContext = createReactorContext;
56
- function extractActorHooks(ActorContext) {
3
+ exports.extractActorContext = void 0;
4
+ const react_1 = require("react");
5
+ function extractActorContext(actorContext) {
57
6
  /**
58
7
  * Hook for accessing the actor context, including the actor manager and state.
59
8
  * @returns The actor context, including the actor manager and state.
@@ -69,12 +18,20 @@ function extractActorHooks(ActorContext) {
69
18
  * </div>
70
19
  * );
71
20
  * }
21
+ *
22
+ * function App() {
23
+ * return (
24
+ * <ActorProvider canisterId="rrkah-fqaaa-aaaaa-aaaaq-cai">
25
+ * <ActorComponent />
26
+ * </ActorProvider>
27
+ * );
28
+ * }
72
29
  * ```
73
30
  */
74
31
  const useActorContext = () => {
75
- const context = (0, react_1.useContext)(ActorContext);
32
+ const context = (0, react_1.useContext)(actorContext);
76
33
  if (!context) {
77
- throw new Error("useActor must be used within a ActorProvider");
34
+ throw new Error("Actor hooks must be used within a ActorProvider");
78
35
  }
79
36
  return context;
80
37
  };
@@ -158,13 +115,6 @@ function extractActorHooks(ActorContext) {
158
115
  * ```
159
116
  */
160
117
  const useUpdateCall = (args) => useActorContext().useUpdateCall(args);
161
- /**
162
- * Hook that combines useVisitMethod and useReactorCall for calling actor methods. It provides both the visit service for the method and the ability to make actor calls with state management.
163
- *
164
- * @param args Configuration object including the function name and arguments for the actor method call.
165
- * @returns An object containing the visit function for the method and the current call state (data, error, loading).
166
- */
167
- const useMethodCall = (args) => useActorContext().useMethodCall(args);
168
118
  /**
169
119
  * Memoizes and returns a visit service function for a specific actor method.
170
120
  *
@@ -176,9 +126,8 @@ function extractActorHooks(ActorContext) {
176
126
  useActorState,
177
127
  useQueryCall,
178
128
  useUpdateCall,
179
- useMethodCall,
180
129
  useVisitMethod,
181
130
  initialize,
182
131
  };
183
132
  }
184
- exports.extractActorHooks = extractActorHooks;
133
+ exports.extractActorContext = extractActorContext;
@@ -0,0 +1,27 @@
1
+ import type { AgentContext, CreateAgentContextReturnType } from "../types";
2
+ /**
3
+ * This function facilitates the use of contextually provided agent functionalities,
4
+ * such as managing the agent's state, authentication state, and user principal.
5
+ *
6
+ * @param agentContext A React context object of type AgentContext or null,
7
+ * typically provided by an AgentProvider at a higher level in the component tree.
8
+ * @returns An object containing the following hooks:
9
+ * - useAgent: Hook for accessing the current agent instance.
10
+ * - useAuthState: Hook for accessing the current authentication state.
11
+ * - useAgentState: Hook for accessing the current state of the agent.
12
+ * - useAuthClient: Hook for accessing the authentication client, optionally accepting arguments for configuration.
13
+ * - useAgentManager: Hook for accessing the AgentManager instance.
14
+ * - useUserPrincipal: Hook for accessing the user's principal.
15
+ *
16
+ * Each hook is designed to be used within components that are descendants of an AgentProvider,
17
+ * ensuring access to the necessary agent-related context.
18
+ *
19
+ * Throws:
20
+ * - Error if used outside of an AgentProvider context.
21
+ *
22
+ * ### Integration
23
+ *
24
+ * To use these hooks, ensure your components are wrapped in an `AgentProvider` that you've set up to supply the `AgentContext`.
25
+ * This context provides the necessary agent functionalities and state management capabilities required by the hooks.
26
+ */
27
+ export declare const extractAgentContext: (agentContext: React.Context<AgentContext | null>) => Omit<CreateAgentContextReturnType, "AgentProvider">;
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.extractAgentContext = void 0;
4
+ const react_1 = require("react");
5
+ /**
6
+ * This function facilitates the use of contextually provided agent functionalities,
7
+ * such as managing the agent's state, authentication state, and user principal.
8
+ *
9
+ * @param agentContext A React context object of type AgentContext or null,
10
+ * typically provided by an AgentProvider at a higher level in the component tree.
11
+ * @returns An object containing the following hooks:
12
+ * - useAgent: Hook for accessing the current agent instance.
13
+ * - useAuthState: Hook for accessing the current authentication state.
14
+ * - useAgentState: Hook for accessing the current state of the agent.
15
+ * - useAuthClient: Hook for accessing the authentication client, optionally accepting arguments for configuration.
16
+ * - useAgentManager: Hook for accessing the AgentManager instance.
17
+ * - useUserPrincipal: Hook for accessing the user's principal.
18
+ *
19
+ * Each hook is designed to be used within components that are descendants of an AgentProvider,
20
+ * ensuring access to the necessary agent-related context.
21
+ *
22
+ * Throws:
23
+ * - Error if used outside of an AgentProvider context.
24
+ *
25
+ * ### Integration
26
+ *
27
+ * To use these hooks, ensure your components are wrapped in an `AgentProvider` that you've set up to supply the `AgentContext`.
28
+ * This context provides the necessary agent functionalities and state management capabilities required by the hooks.
29
+ */
30
+ const extractAgentContext = (agentContext) => {
31
+ const useAgentContext = (mybeAgentContext) => {
32
+ const context = (0, react_1.useContext)(mybeAgentContext || agentContext);
33
+ if (!context) {
34
+ throw new Error("Agent hooks must be used within a AgentProvider");
35
+ }
36
+ return context;
37
+ };
38
+ /**
39
+ * Accesses the `AgentManager` instance for managing agent configurations and state.
40
+ *
41
+ * @example
42
+ *```jsx
43
+ * function AgentManagerComponent() {
44
+ * const agentManager = useAgentManager();
45
+ *
46
+ * // Use agentManager for managing agent configurations, etc.
47
+ * return <div>Agent Manager ready.</div>;
48
+ * }
49
+ *```
50
+ */
51
+ const useAgentManager = (agentContext) => {
52
+ const context = useAgentContext(agentContext);
53
+ return context.agentManager;
54
+ };
55
+ /**
56
+ * Accesses the current agent instance.
57
+ *
58
+ * @example
59
+ *```jsx
60
+ * function AgentComponent() {
61
+ * const agent = useAgent();
62
+ *
63
+ * // Use agent for interacting with the Internet Computer.
64
+ * return <div>Agent ready.</div>;
65
+ * }
66
+ *```
67
+ */
68
+ const useAgent = () => useAgentContext().useAgent();
69
+ /**
70
+ * Accesses the current authentication state.
71
+ *
72
+ * @example
73
+ * ```jsx
74
+ * function AuthStateComponent() {
75
+ * const { isAuthenticated, user } = useAuthState();
76
+ *
77
+ * return (
78
+ * <div>
79
+ * {isAuthenticated ? `User ${user} is authenticated.` : 'User is not authenticated.'}
80
+ * </div>
81
+ * );
82
+ * }
83
+ * ```
84
+ */
85
+ const useAuthState = () => useAgentContext().useAuthState();
86
+ /**
87
+ * Accesses the current state of the agent.
88
+ *
89
+ * @example
90
+ * ```jsx
91
+ * function AgentStateComponent() {
92
+ * const { initialized, initializing } = useAgentState();
93
+ *
94
+ * return (
95
+ * <div>
96
+ * {initialized
97
+ * ? 'Agent is initialized.'
98
+ * : initializing
99
+ * ? 'Agent is initializing...'
100
+ * : 'Agent is not initialized.'}
101
+ * </div>
102
+ * );
103
+ * }
104
+ * ```
105
+ */
106
+ const useAgentState = () => useAgentContext().useAgentState();
107
+ const useAuthClient = (args) => useAgentContext().useAuthClient(args);
108
+ /**
109
+ * Accesses the user's principal.
110
+ *
111
+ * @example
112
+ * ```jsx
113
+ * function UserPrincipalComponent() {
114
+ * const userPrincipal = useUserPrincipal();
115
+ *
116
+ * return (
117
+ * <div>
118
+ * {userPrincipal ? `User principal: ${userPrincipal}` : 'User principal not found.'}
119
+ * </div>
120
+ * );
121
+ * }
122
+ * ```
123
+ */
124
+ const useUserPrincipal = () => useAgentContext().useUserPrincipal();
125
+ return {
126
+ useAgent,
127
+ useAuthState,
128
+ useAgentState,
129
+ useAuthClient,
130
+ useAgentManager,
131
+ useUserPrincipal,
132
+ };
133
+ };
134
+ exports.extractAgentContext = extractAgentContext;
@@ -1,3 +1,5 @@
1
- export * from "./agent";
2
- export * from "./actor";
3
- export * from "./auth";
1
+ export * from "./agentHooks";
2
+ export * from "./actorHooks";
3
+ export * from "./authHooks";
4
+ export * from "./extractActorContext";
5
+ export * from "./extractAgentContext";
@@ -14,6 +14,8 @@ 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("./agent"), exports);
18
- __exportStar(require("./actor"), exports);
19
- __exportStar(require("./auth"), exports);
17
+ __exportStar(require("./agentHooks"), exports);
18
+ __exportStar(require("./actorHooks"), exports);
19
+ __exportStar(require("./authHooks"), exports);
20
+ __exportStar(require("./extractActorContext"), exports);
21
+ __exportStar(require("./extractAgentContext"), exports);