@ic-reactor/react 1.0.3 → 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.
- package/README.md +8 -17
- package/dist/helpers/actorHooks.d.ts +18 -0
- package/dist/helpers/{actor.js → actorHooks.js} +29 -19
- package/dist/helpers/agentHooks.d.ts +3 -0
- package/dist/helpers/{agent.js → agentHooks.js} +3 -3
- package/dist/helpers/authHooks.d.ts +2 -0
- package/dist/helpers/authHooks.js +127 -0
- package/dist/helpers/extractActorContext.d.ts +3 -0
- package/dist/helpers/extractActorContext.js +133 -0
- package/dist/helpers/extractAgentContext.d.ts +27 -0
- package/dist/helpers/extractAgentContext.js +134 -0
- package/dist/helpers/index.d.ts +5 -3
- package/dist/helpers/index.js +5 -3
- package/dist/helpers/types.d.ts +32 -37
- package/dist/index.d.ts +0 -1
- package/dist/index.js +0 -1
- package/dist/main.d.ts +38 -2
- package/dist/main.js +39 -21
- package/dist/provider/ActorProvider.d.ts +27 -0
- package/dist/provider/ActorProvider.js +30 -0
- package/dist/provider/AgentProvider.d.ts +30 -0
- package/dist/provider/AgentProvider.js +33 -0
- package/dist/provider/actor.d.ts +64 -0
- package/dist/provider/actor.js +117 -0
- package/dist/provider/agent.d.ts +71 -0
- package/dist/provider/agent.js +124 -0
- package/dist/provider/hooks/index.d.ts +1 -0
- package/dist/provider/{agent → hooks}/index.js +1 -2
- package/dist/provider/hooks/types.d.ts +15 -0
- package/dist/provider/hooks/useActor.d.ts +63 -0
- package/dist/provider/hooks/useActor.js +143 -0
- package/dist/provider/index.d.ts +8 -2
- package/dist/provider/index.js +9 -2
- package/dist/provider/types.d.ts +27 -0
- package/dist/{hooks/index.js → provider/types.js} +1 -2
- package/dist/types.d.ts +8 -7
- package/dist/types.js +2 -3
- package/package.json +3 -3
- package/dist/helpers/actor.d.ts +0 -4
- package/dist/helpers/agent.d.ts +0 -6
- package/dist/helpers/auth.d.ts +0 -7
- package/dist/helpers/auth.js +0 -108
- package/dist/hooks/index.d.ts +0 -2
- package/dist/hooks/useCandid.d.ts +0 -18
- package/dist/hooks/useCandid.js +0 -54
- package/dist/hooks/useReactor.d.ts +0 -19
- package/dist/hooks/useReactor.js +0 -46
- package/dist/provider/actor/index.d.ts +0 -15
- package/dist/provider/actor/index.js +0 -87
- package/dist/provider/actor/types.d.ts +0 -21
- package/dist/provider/agent/context.d.ts +0 -7
- package/dist/provider/agent/context.js +0 -56
- package/dist/provider/agent/hooks.d.ts +0 -12
- package/dist/provider/agent/hooks.js +0 -43
- package/dist/provider/agent/index.d.ts +0 -2
- package/dist/provider/agent/types.d.ts +0 -12
- package/dist/provider/agent/types.js +0 -2
- /package/dist/provider/{actor → 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
|
-
//
|
|
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
|
|
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 "./
|
|
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={
|
|
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 "./
|
|
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={
|
|
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>
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { ActorHooksReturnType } from "../types";
|
|
2
|
+
import type { ActorManager, BaseActor } from "@ic-reactor/core/dist/types";
|
|
3
|
+
/**
|
|
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.
|
|
5
|
+
*
|
|
6
|
+
* @param actorManager An instance of ActorManager containing methods and properties to manage actors, including the actorStore, canisterId, visitFunction, callMethod, and initialize function.
|
|
7
|
+
* @returns An object containing several hooks and utility functions for interacting with actors, managing state, and invoking actor methods.
|
|
8
|
+
*
|
|
9
|
+
* Hooks included:
|
|
10
|
+
* - initialize: Function to initialize actor management.
|
|
11
|
+
* - useActorState: Hook for accessing the actor's state including the canister ID.
|
|
12
|
+
* - useVisitMethod: Hook for memoizing a method visit service for a given actor method name.
|
|
13
|
+
* - useQueryCall: Hook specifically designed for query calls to actors with features such as automatic refetching on mount and at specified intervals.
|
|
14
|
+
* - useUpdateCall: Hook specifically designed for update calls to actors with features such as error handling and loading state management.
|
|
15
|
+
*
|
|
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.
|
|
17
|
+
*/
|
|
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.
|
|
23
|
+
exports.actorHooks = void 0;
|
|
24
24
|
const react_1 = require("react");
|
|
25
25
|
const zustand_1 = require("zustand");
|
|
26
26
|
const DEFAULT_STATE = {
|
|
@@ -28,19 +28,34 @@ const DEFAULT_STATE = {
|
|
|
28
28
|
error: undefined,
|
|
29
29
|
loading: false,
|
|
30
30
|
};
|
|
31
|
-
|
|
31
|
+
/**
|
|
32
|
+
* 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.
|
|
33
|
+
*
|
|
34
|
+
* @param actorManager An instance of ActorManager containing methods and properties to manage actors, including the actorStore, canisterId, visitFunction, callMethod, and initialize function.
|
|
35
|
+
* @returns An object containing several hooks and utility functions for interacting with actors, managing state, and invoking actor methods.
|
|
36
|
+
*
|
|
37
|
+
* Hooks included:
|
|
38
|
+
* - initialize: Function to initialize actor management.
|
|
39
|
+
* - useActorState: Hook for accessing the actor's state including the canister ID.
|
|
40
|
+
* - useVisitMethod: Hook for memoizing a method visit service for a given actor method name.
|
|
41
|
+
* - useQueryCall: Hook specifically designed for query calls to actors with features such as automatic refetching on mount and at specified intervals.
|
|
42
|
+
* - useUpdateCall: Hook specifically designed for update calls to actors with features such as error handling and loading state management.
|
|
43
|
+
*
|
|
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.
|
|
45
|
+
*/
|
|
46
|
+
const actorHooks = (actorManager) => {
|
|
32
47
|
const { actorStore, canisterId, visitFunction, callMethod, initialize } = actorManager;
|
|
33
48
|
const useActorState = () => (Object.assign(Object.assign({}, (0, zustand_1.useStore)(actorStore)), { canisterId }));
|
|
34
49
|
const useVisitMethod = (functionName) => {
|
|
35
50
|
return (0, react_1.useMemo)(() => visitFunction[functionName], [functionName]);
|
|
36
51
|
};
|
|
37
|
-
const
|
|
52
|
+
const useMethodCall = (_a) => {
|
|
38
53
|
var { args = [], functionName, throwOnError = false } = _a, events = __rest(_a, ["args", "functionName", "throwOnError"]);
|
|
39
54
|
const [state, setState] = (0, react_1.useState)(DEFAULT_STATE);
|
|
40
55
|
const reset = (0, react_1.useCallback)(() => setState(DEFAULT_STATE), []);
|
|
41
56
|
const call = (0, react_1.useCallback)((eventOrReplaceArgs) => __awaiter(void 0, void 0, void 0, function* () {
|
|
42
57
|
var _b, _c, _d, _e, _f;
|
|
43
|
-
setState(
|
|
58
|
+
setState((prev) => (Object.assign(Object.assign({}, prev), { error: undefined, loading: true })));
|
|
44
59
|
(_b = events === null || events === void 0 ? void 0 : events.onLoading) === null || _b === void 0 ? void 0 : _b.call(events, true);
|
|
45
60
|
try {
|
|
46
61
|
const replaceArgs = eventOrReplaceArgs instanceof Array ? eventOrReplaceArgs : args;
|
|
@@ -59,36 +74,31 @@ const getActorHooks = (actorManager) => {
|
|
|
59
74
|
if (throwOnError)
|
|
60
75
|
throw error;
|
|
61
76
|
}
|
|
62
|
-
}), [args, functionName, events
|
|
77
|
+
}), [args, functionName, events]);
|
|
63
78
|
return Object.assign({ call, reset }, state);
|
|
64
79
|
};
|
|
65
80
|
const useQueryCall = (_a) => {
|
|
66
81
|
var { refetchOnMount = true, refetchInterval = false } = _a, rest = __rest(_a, ["refetchOnMount", "refetchInterval"]);
|
|
67
|
-
const _b =
|
|
82
|
+
const _b = useMethodCall(rest), { call } = _b, state = __rest(_b, ["call"]);
|
|
68
83
|
const intervalId = (0, react_1.useRef)();
|
|
69
84
|
(0, react_1.useEffect)(() => {
|
|
70
|
-
if (refetchInterval)
|
|
85
|
+
if (refetchInterval) {
|
|
71
86
|
intervalId.current = setInterval(call, refetchInterval);
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
(0, react_1.useLayoutEffect)(() => {
|
|
75
|
-
if (refetchOnMount)
|
|
87
|
+
}
|
|
88
|
+
if (refetchOnMount) {
|
|
76
89
|
call();
|
|
77
|
-
|
|
90
|
+
}
|
|
91
|
+
return () => clearInterval(intervalId.current);
|
|
92
|
+
}, [refetchInterval, refetchOnMount]);
|
|
78
93
|
return Object.assign({ call }, state);
|
|
79
94
|
};
|
|
80
|
-
const useUpdateCall =
|
|
81
|
-
const useMethodCall = (args) => {
|
|
82
|
-
const visit = useVisitMethod(args.functionName);
|
|
83
|
-
return Object.assign({ visit }, useReactorCall(args));
|
|
84
|
-
};
|
|
95
|
+
const useUpdateCall = useMethodCall;
|
|
85
96
|
return {
|
|
86
97
|
initialize,
|
|
87
98
|
useQueryCall,
|
|
88
99
|
useUpdateCall,
|
|
89
100
|
useActorState,
|
|
90
|
-
useMethodCall,
|
|
91
101
|
useVisitMethod,
|
|
92
102
|
};
|
|
93
103
|
};
|
|
94
|
-
exports.
|
|
104
|
+
exports.actorHooks = actorHooks;
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.
|
|
3
|
+
exports.agentHooks = void 0;
|
|
4
4
|
const react_1 = require("react");
|
|
5
5
|
const zustand_1 = require("zustand");
|
|
6
|
-
const
|
|
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.
|
|
19
|
+
exports.agentHooks = agentHooks;
|
|
@@ -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">;
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.extractActorContext = void 0;
|
|
4
|
+
const react_1 = require("react");
|
|
5
|
+
function extractActorContext(actorContext) {
|
|
6
|
+
/**
|
|
7
|
+
* Hook for accessing the actor context, including the actor manager and state.
|
|
8
|
+
* @returns The actor context, including the actor manager and state.
|
|
9
|
+
* @example
|
|
10
|
+
* ```tsx
|
|
11
|
+
* function ActorComponent() {
|
|
12
|
+
* const { initialize, useActorState, useQueryCall, useUpdateCall, useMethodCall, useVisitMethod } = useActorContext();
|
|
13
|
+
* const { canisterId } = useActorState();
|
|
14
|
+
*
|
|
15
|
+
* return (
|
|
16
|
+
* <div>
|
|
17
|
+
* <p>Canister ID: {canisterId}</p>
|
|
18
|
+
* </div>
|
|
19
|
+
* );
|
|
20
|
+
* }
|
|
21
|
+
*
|
|
22
|
+
* function App() {
|
|
23
|
+
* return (
|
|
24
|
+
* <ActorProvider canisterId="rrkah-fqaaa-aaaaa-aaaaq-cai">
|
|
25
|
+
* <ActorComponent />
|
|
26
|
+
* </ActorProvider>
|
|
27
|
+
* );
|
|
28
|
+
* }
|
|
29
|
+
* ```
|
|
30
|
+
*/
|
|
31
|
+
const useActorContext = () => {
|
|
32
|
+
const context = (0, react_1.useContext)(actorContext);
|
|
33
|
+
if (!context) {
|
|
34
|
+
throw new Error("Actor hooks must be used within a ActorProvider");
|
|
35
|
+
}
|
|
36
|
+
return context;
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* Initializes the actor manager, setting up the actor's state.
|
|
40
|
+
*/
|
|
41
|
+
const initialize = () => useActorContext().initialize();
|
|
42
|
+
/**
|
|
43
|
+
* Hook for accessing the current state of the actor, including the canister ID.
|
|
44
|
+
*
|
|
45
|
+
* @returns An object containing the current state of the actor from Zustand's store and the canister ID.
|
|
46
|
+
* @example
|
|
47
|
+
* ```tsx
|
|
48
|
+
* function ActorStateComponent() {
|
|
49
|
+
* const { canisterId, initializing, error, initialized } = useActorState();
|
|
50
|
+
*
|
|
51
|
+
* return (
|
|
52
|
+
* <div>
|
|
53
|
+
* <p>Canister ID: {canisterId}</p>
|
|
54
|
+
* <p>Initializing: {initializing.toString()}</p>
|
|
55
|
+
* <p>Initialized: {initialized.toString()}</p>
|
|
56
|
+
* <p>Error: {error?.message}</p>
|
|
57
|
+
* </div>
|
|
58
|
+
* );
|
|
59
|
+
* }
|
|
60
|
+
*```
|
|
61
|
+
*/
|
|
62
|
+
const useActorState = () => useActorContext().useActorState();
|
|
63
|
+
/**
|
|
64
|
+
* Hook for making query calls to actors. It supports automatic refetching on component mount and at specified intervals.
|
|
65
|
+
*
|
|
66
|
+
* @param options Configuration object for the query call, including refetching options and other configurations passed to useReactorCall.
|
|
67
|
+
* @returns An object containing the query call function and the current call state (data, error, loading, call, reset).
|
|
68
|
+
* @example
|
|
69
|
+
* ```tsx
|
|
70
|
+
* function QueryCallComponent() {
|
|
71
|
+
* const { call, data, loading } = useQueryCall({
|
|
72
|
+
* functionName: 'getUserProfile',
|
|
73
|
+
* args: ['123'],
|
|
74
|
+
* refetchOnMount: true,
|
|
75
|
+
* refetchInterval: 5000, // refetch every 5 seconds
|
|
76
|
+
* });
|
|
77
|
+
*
|
|
78
|
+
* if (loading) return <p>Loading profile...</p>;
|
|
79
|
+
*
|
|
80
|
+
* return (
|
|
81
|
+
* <div>
|
|
82
|
+
* <p>User Profile: {JSON.stringify(data)}</p>
|
|
83
|
+
* <button onClick={call}>Refetch</button>
|
|
84
|
+
* </div>
|
|
85
|
+
* );
|
|
86
|
+
* }
|
|
87
|
+
* ```
|
|
88
|
+
*/
|
|
89
|
+
const useQueryCall = (args) => useActorContext().useQueryCall(args);
|
|
90
|
+
/**
|
|
91
|
+
* Hook for making update calls to actors, handling loading states, and managing errors. It supports custom event handlers for loading, success, and error events.
|
|
92
|
+
*
|
|
93
|
+
* @param options Configuration object for the actor method call, including the method name, arguments, and event handlers.
|
|
94
|
+
* @returns An object containing the method call function, a reset function to reset the call state to its default, and the current call state (data, error, loading, call, reset).
|
|
95
|
+
* @example
|
|
96
|
+
* ```tsx
|
|
97
|
+
* function UpdateCallComponent() {
|
|
98
|
+
* const { call, data, loading } = useUpdateCall({
|
|
99
|
+
* functionName: 'updateUserProfile',
|
|
100
|
+
* args: ['123', { name: 'John Doe' }],
|
|
101
|
+
* onLoading: (loading) => console.log('Loading:', loading),
|
|
102
|
+
* onError: (error) => console.error('Error:', error),
|
|
103
|
+
* onSuccess: (data) => console.log('Success:', data),
|
|
104
|
+
* });
|
|
105
|
+
*
|
|
106
|
+
* if (loading) return <p>Updating profile...</p>;
|
|
107
|
+
*
|
|
108
|
+
* return (
|
|
109
|
+
* <div>
|
|
110
|
+
* <p>Updated Profile: {JSON.stringify(data)}</p>
|
|
111
|
+
* <button onClick={call}>Update</button>
|
|
112
|
+
* </div>
|
|
113
|
+
* );
|
|
114
|
+
* }
|
|
115
|
+
* ```
|
|
116
|
+
*/
|
|
117
|
+
const useUpdateCall = (args) => useActorContext().useUpdateCall(args);
|
|
118
|
+
/**
|
|
119
|
+
* Memoizes and returns a visit service function for a specific actor method.
|
|
120
|
+
*
|
|
121
|
+
* @param functionName The name of the actor method to visit.
|
|
122
|
+
* @returns The visit service function for the specified method.
|
|
123
|
+
*/
|
|
124
|
+
const useVisitMethod = (functionName) => useActorContext().useVisitMethod(functionName);
|
|
125
|
+
return {
|
|
126
|
+
useActorState,
|
|
127
|
+
useQueryCall,
|
|
128
|
+
useUpdateCall,
|
|
129
|
+
useVisitMethod,
|
|
130
|
+
initialize,
|
|
131
|
+
};
|
|
132
|
+
}
|
|
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;
|
package/dist/helpers/index.d.ts
CHANGED
package/dist/helpers/index.js
CHANGED
|
@@ -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("./
|
|
18
|
-
__exportStar(require("./
|
|
19
|
-
__exportStar(require("./
|
|
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);
|