@ic-reactor/react 0.4.0 → 0.4.2

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 CHANGED
@@ -33,15 +33,16 @@ First, create an actor declaration file:
33
33
  ```ts
34
34
  // store.ts
35
35
  import { canisterId, idlFactory, actor } from "declaration/actor"
36
- import { createReActor } from "@ic-reactor/core"
36
+ import { createReActor } from "@ic-reactor/react"
37
37
 
38
38
  type Actor = typeof actor
39
39
 
40
- export const { useActorStore, useQueryCall } = createReActor<Actor>({
41
- canisterId: "rrkah-fqaaa-aaaaa-aaaaq-cai",
42
- idlFactory,
43
- host: "https://localhost:4943",
44
- })
40
+ export const { useActorStore, useAuthClient, useQueryCall } =
41
+ createReActor<Actor>({
42
+ canisterId: "rrkah-fqaaa-aaaaa-aaaaq-cai",
43
+ idlFactory,
44
+ host: "https://localhost:4943",
45
+ })
45
46
  ```
46
47
 
47
48
  Then, use the `useQueryCall` hook to call your canister method:
@@ -54,7 +55,11 @@ const Balance = ({ principal }) => {
54
55
  const { call, data, loading, error } = useQueryCall({
55
56
  functionName: "get_balance",
56
57
  args: [principal],
57
- callOnMount: true,
58
+ refetchInterval: 1000,
59
+ refetchOnMount: true,
60
+ onLoading: () => console.log("Loading..."),
61
+ onSuccess: (data) => console.log("Success!", data),
62
+ onError: (error) => console.log("Error!", error),
58
63
  })
59
64
 
60
65
  return (
@@ -72,6 +77,61 @@ const Balance = ({ principal }) => {
72
77
  export default Balance
73
78
  ```
74
79
 
80
+ ## Authentication
81
+
82
+ `@ic-reactor/react` provides a custom hook for managing authentication with the IC blockchain. To use it, first create an authentication declaration file:
83
+
84
+ ```jsx
85
+ // Login.tsx
86
+ import { useAuthClient } from "./store"
87
+
88
+ const Login = () => {
89
+ const {
90
+ login,
91
+ logout,
92
+ loginLoading,
93
+ loginError,
94
+ identity,
95
+ authenticating,
96
+ authenticated,
97
+ } = useAuthClient()
98
+
99
+ return (
100
+ <div>
101
+ <h2>Login:</h2>
102
+ <div>
103
+ {loginLoading && <div>Loading...</div>}
104
+ {loginError ? <div>{JSON.stringify(loginError)}</div> : null}
105
+ {identity && <div>{identity.getPrincipal().toText()}</div>}
106
+ </div>
107
+ {authenticated ? (
108
+ <div>
109
+ <button onClick={() => logout()}>Logout</button>
110
+ </div>
111
+ ) : (
112
+ <div>
113
+ <button
114
+ onClick={() =>
115
+ login({
116
+ identityProvider:
117
+ process.env.DFX_NETWORK === "ic"
118
+ ? "https://identity.ic0.app/#authorize"
119
+ : "http://rdmx6-jaaaa-aaaaa-aaadq-cai.localhost:4943/#authorize",
120
+ })
121
+ }
122
+ disabled={authenticating}
123
+ >
124
+ Login
125
+ </button>
126
+ </div>
127
+ )}
128
+ </div>
129
+ )
130
+ }
131
+
132
+ export default Login
133
+ ```
134
+
75
135
  ## API Reference
76
136
 
77
137
  The library provides various hooks and utilities for interacting with IC actors:
@@ -13,7 +13,7 @@ exports.getAuthHooks = void 0;
13
13
  const react_1 = require("react");
14
14
  const zustand_1 = require("zustand");
15
15
  const getAuthHooks = (agentManager) => {
16
- const { authenticate, authStore } = agentManager;
16
+ const { authenticate, authStore, isLocalEnv } = agentManager;
17
17
  const useAgentManager = () => {
18
18
  return agentManager;
19
19
  };
@@ -29,7 +29,9 @@ const getAuthHooks = (agentManager) => {
29
29
  setLoginLoading(true);
30
30
  setLoginError(null);
31
31
  try {
32
- yield (authClient === null || authClient === void 0 ? void 0 : authClient.login(Object.assign(Object.assign({}, options), { onSuccess: () => __awaiter(void 0, void 0, void 0, function* () {
32
+ yield (authClient === null || authClient === void 0 ? void 0 : authClient.login(Object.assign(Object.assign({ identityProvider: isLocalEnv
33
+ ? "https://identity.ic0.app/#authorize"
34
+ : "http://rdmx6-jaaaa-aaaaa-aaadq-cai.localhost:4943/#authorize" }, options), { onSuccess: () => __awaiter(void 0, void 0, void 0, function* () {
33
35
  var _a;
34
36
  setLoginLoading(false);
35
37
  yield authenticate();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ic-reactor/react",
3
- "version": "0.4.0",
3
+ "version": "0.4.2",
4
4
  "description": "A React library for interacting with Dfinity actors",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -35,7 +35,7 @@
35
35
  "node": ">=10"
36
36
  },
37
37
  "dependencies": {
38
- "@ic-reactor/store": "^0.4.0",
38
+ "@ic-reactor/store": "^0.4.2",
39
39
  "zustand-utils": "^1.3"
40
40
  },
41
41
  "peerDependencies": {
@@ -48,5 +48,5 @@
48
48
  "react": ">=16.8",
49
49
  "zustand": "4.4"
50
50
  },
51
- "gitHead": "b91b8bec6e0329d0a7cde22014d9222814311f23"
51
+ "gitHead": "d5817736d25a997a1b09f27f7546e8539cf5a6c2"
52
52
  }
@@ -1,14 +0,0 @@
1
- import React, { PropsWithChildren } from "react";
2
- import { type ReActorHooks } from "./index";
3
- import { IDL } from "@dfinity/candid";
4
- import { ActorSubclass, CreateReActorOptions } from "@ic-reactor/store";
5
- export type ActorContextType<A = ActorSubclass<any>> = ReActorHooks<A>;
6
- export declare const ActorContext: React.Context<ActorContextType<any> | null>;
7
- type UseReActorType = <A = ActorSubclass<any>>() => ActorContextType<A>;
8
- export declare const useActor: UseReActorType;
9
- interface ActorProviderProps extends PropsWithChildren, Omit<CreateReActorOptions, "idlFactory"> {
10
- idlFactory?: IDL.InterfaceFactory;
11
- loadingComponent?: React.ReactNode;
12
- }
13
- export declare const ActorProvider: React.FC<ActorProviderProps>;
14
- export {};
@@ -1,118 +0,0 @@
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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
- return new (P || (P = Promise))(function (resolve, reject) {
28
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
- step((generator = generator.apply(thisArg, _arguments || [])).next());
32
- });
33
- };
34
- var __rest = (this && this.__rest) || function (s, e) {
35
- var t = {};
36
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
37
- t[p] = s[p];
38
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
39
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
40
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
41
- t[p[i]] = s[p[i]];
42
- }
43
- return t;
44
- };
45
- Object.defineProperty(exports, "__esModule", { value: true });
46
- exports.ActorProvider = exports.useActor = exports.ActorContext = void 0;
47
- const react_1 = __importStar(require("react"));
48
- const index_1 = require("./index");
49
- const store_1 = require("@ic-reactor/store");
50
- const agentContext_1 = require("./agentContext");
51
- exports.ActorContext = (0, react_1.createContext)(null);
52
- const useActor = () => {
53
- const context = (0, react_1.useContext)(exports.ActorContext);
54
- if (!context) {
55
- throw new Error("useReActor must be used within a ActorProvider");
56
- }
57
- return context;
58
- };
59
- exports.useActor = useActor;
60
- const ActorProvider = (_a) => {
61
- var { children, canisterId, loadingComponent = react_1.default.createElement("div", null, "Loading...") } = _a, config = __rest(_a, ["children", "canisterId", "loadingComponent"]);
62
- const agentManager = (0, agentContext_1.useAgentManager)();
63
- const [didJs, setDidJS] = (0, react_1.useState)();
64
- const fetchDidJs = (0, react_1.useCallback)(() => __awaiter(void 0, void 0, void 0, function* () {
65
- if (!canisterId) {
66
- throw new Error("canisterId is required");
67
- }
68
- const agent = agentManager.getAgent();
69
- (0, store_1.getDidJsFromMetadata)(agent, canisterId).then((idlFactory) => __awaiter(void 0, void 0, void 0, function* () {
70
- if (!idlFactory) {
71
- try {
72
- idlFactory = yield (0, store_1.getDidJsFromTmpHack)(agent, canisterId);
73
- }
74
- catch (err) {
75
- if (/no query method/.test(err)) {
76
- console.warn(err);
77
- idlFactory = undefined;
78
- }
79
- else {
80
- throw err;
81
- }
82
- }
83
- if (!idlFactory) {
84
- console.warn("No query method found for canister", canisterId);
85
- }
86
- }
87
- setDidJS(idlFactory);
88
- }));
89
- return didJs;
90
- }), [canisterId]);
91
- (0, react_1.useEffect)(() => {
92
- const { idlFactory } = config;
93
- if (idlFactory) {
94
- setDidJS({ idlFactory });
95
- return;
96
- }
97
- fetchDidJs();
98
- }, [fetchDidJs, config.idlFactory]);
99
- const hooks = (0, react_1.useMemo)(() => {
100
- if (!didJs) {
101
- return null;
102
- }
103
- try {
104
- return (0, index_1.createReActor)({
105
- idlFactory: didJs.idlFactory,
106
- agentManager,
107
- canisterId,
108
- withDevtools: config.withDevtools,
109
- });
110
- }
111
- catch (err) {
112
- console.error(err);
113
- return null;
114
- }
115
- }, [canisterId, agentManager, didJs]);
116
- return (react_1.default.createElement(exports.ActorContext.Provider, { value: hooks }, hooks === null ? loadingComponent : children));
117
- };
118
- exports.ActorProvider = ActorProvider;
@@ -1,14 +0,0 @@
1
- import React, { PropsWithChildren } from "react";
2
- import { AgentManager, AgentManagerOptions } from "@ic-reactor/store";
3
- import { getAuthHooks } from "./hooks/auth";
4
- export type AgentContextType = ReturnType<typeof getAuthHooks> & {
5
- agentManager: AgentManager;
6
- };
7
- export declare const AgentContext: React.Context<AgentContextType | null>;
8
- export declare const useAgent: () => AgentContextType;
9
- export declare const useAgentManager: () => AgentManager;
10
- interface ReActorProviderProps extends PropsWithChildren, AgentManagerOptions {
11
- agentManager?: AgentManager;
12
- }
13
- export declare const AgentProvider: React.FC<ReActorProviderProps>;
14
- export {};
@@ -1,67 +0,0 @@
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
- Object.defineProperty(exports, "__esModule", { value: true });
37
- exports.AgentProvider = exports.useAgentManager = exports.useAgent = exports.AgentContext = void 0;
38
- const react_1 = __importStar(require("react"));
39
- const store_1 = require("@ic-reactor/store");
40
- const auth_1 = require("./hooks/auth");
41
- exports.AgentContext = (0, react_1.createContext)(null);
42
- const useAgent = () => {
43
- const context = (0, react_1.useContext)(exports.AgentContext);
44
- if (!context) {
45
- throw new Error("useAgent must be used within a AgentProvider");
46
- }
47
- return context;
48
- };
49
- exports.useAgent = useAgent;
50
- const useAgentManager = () => {
51
- const context = (0, react_1.useContext)(exports.AgentContext);
52
- if (!context) {
53
- throw new Error("useAgentManager must be used within a AgentProvider");
54
- }
55
- return context.agentManager;
56
- };
57
- exports.useAgentManager = useAgentManager;
58
- const AgentProvider = (_a) => {
59
- var { children } = _a, config = __rest(_a, ["children"]);
60
- const agentManager = (0, react_1.useRef)(config.agentManager || (0, store_1.createAgentManager)(config));
61
- const hooks = (0, react_1.useMemo)(() => {
62
- const hooks = (0, auth_1.getAuthHooks)(agentManager.current);
63
- return Object.assign(Object.assign({}, hooks), { agentManager: agentManager.current });
64
- }, []);
65
- return react_1.default.createElement(exports.AgentContext.Provider, { value: hooks }, children);
66
- };
67
- exports.AgentProvider = AgentProvider;
@@ -1,41 +0,0 @@
1
- import type { AuthClientLoginOptions } from "@dfinity/auth-client";
2
- import type { CreateReActorOptions } from "@ic-reactor/store";
3
- export * from "./context";
4
- export declare const createReActor: <A extends unknown>(options: Omit<CreateReActorOptions, "isLocal">) => {
5
- useMethodFields: () => import("@ic-reactor/store").ActorMethodField<A>[];
6
- useMethodField: (functionName: keyof A & string) => import("@ic-reactor/store").ActorMethodField<A> | undefined;
7
- useActorStore: () => {
8
- initialized: boolean;
9
- initializing: boolean;
10
- error: Error | undefined;
11
- methodState: import("@ic-reactor/store").ActorMethodStates<A>;
12
- };
13
- useAuthStore: () => import("@ic-reactor/store").ActorAuthState;
14
- useQueryCall: <M extends keyof A>({ autoRefresh, refreshInterval, disableInitialCall, ...rest }: import("./types").ReActorUseQueryArgs<A, M>) => {
15
- data: import("@ic-reactor/store").ExtractActorMethodReturnType<A[M]> | undefined;
16
- error: Error | undefined;
17
- loading: boolean;
18
- field: import("@ic-reactor/store").ActorMethodField<A> | undefined;
19
- call: (replaceArgs?: import("@ic-reactor/store").ExtractActorMethodArgs<A[M]> | undefined) => Promise<import("@ic-reactor/store").ExtractActorMethodReturnType<A[M]> | undefined>;
20
- };
21
- useUpdateCall: <M_1 extends keyof A>(args: import("./types").ReActorUseUpdateArgs<A, M_1>) => {
22
- data: import("@ic-reactor/store").ExtractActorMethodReturnType<A[M_1]> | undefined;
23
- error: Error | undefined;
24
- loading: boolean;
25
- call: (replaceArgs?: import("@ic-reactor/store").ExtractActorMethodArgs<A[M_1]> | undefined) => Promise<import("@ic-reactor/store").ExtractActorMethodReturnType<A[M_1]> | undefined>;
26
- field: import("@ic-reactor/store").ActorMethodField<A> | undefined;
27
- };
28
- useAuthClient: () => {
29
- authClient: import("@dfinity/auth-client").AuthClient | null;
30
- authenticated: boolean;
31
- authenticating: boolean;
32
- identity: import("@ic-reactor/store").Identity | null;
33
- login: (options?: AuthClientLoginOptions) => Promise<void>;
34
- logout: (options?: {
35
- returnTo?: string;
36
- }) => Promise<void>;
37
- authenticate: () => Promise<void>;
38
- loginLoading: boolean;
39
- loginError: unknown;
40
- };
41
- };
package/dist/authHooks.js DELETED
@@ -1,102 +0,0 @@
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 __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
17
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
18
- return new (P || (P = Promise))(function (resolve, reject) {
19
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
20
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
21
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
22
- step((generator = generator.apply(thisArg, _arguments || [])).next());
23
- });
24
- };
25
- Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.createReActor = void 0;
27
- const store_1 = require("@ic-reactor/store");
28
- const react_1 = require("react");
29
- const zustand_1 = require("zustand");
30
- const hooks_1 = require("./hooks");
31
- __exportStar(require("./context"), exports);
32
- const createReActor = (options) => {
33
- const isLocal = typeof process !== "undefined" &&
34
- (process.env.NODE_ENV === "development" ||
35
- process.env.DFX_NETWORK === "local");
36
- const { authenticate, authStore, callMethod, actorStore, methodFields } = (0, store_1.createReActorStore)(Object.assign({ isLocal }, options));
37
- const useActorStore = () => {
38
- const actorState = (0, zustand_1.useStore)(actorStore, (state) => state);
39
- return Object.assign({}, actorState);
40
- };
41
- const useAuthStore = () => {
42
- const authState = (0, zustand_1.useStore)(authStore, (state) => state);
43
- return authState;
44
- };
45
- const useAuthClient = () => {
46
- const [loginLoading, setLoginLoading] = (0, react_1.useState)(false);
47
- const [loginError, setLoginError] = (0, react_1.useState)(null);
48
- const { authClient, authenticated, authenticating, identity } = useAuthStore();
49
- const login = (options) => __awaiter(void 0, void 0, void 0, function* () {
50
- setLoginLoading(true);
51
- setLoginError(null);
52
- try {
53
- yield (authClient === null || authClient === void 0 ? void 0 : authClient.login(Object.assign(Object.assign({}, options), { onSuccess: () => __awaiter(void 0, void 0, void 0, function* () {
54
- var _a;
55
- setLoginLoading(false);
56
- yield authenticate();
57
- (_a = options === null || options === void 0 ? void 0 : options.onSuccess) === null || _a === void 0 ? void 0 : _a.call(options);
58
- }), onError: (e) => {
59
- var _a;
60
- setLoginError(e);
61
- setLoginLoading(false);
62
- (_a = options === null || options === void 0 ? void 0 : options.onError) === null || _a === void 0 ? void 0 : _a.call(options, e);
63
- } })));
64
- }
65
- catch (e) {
66
- setLoginLoading(false);
67
- setLoginError(e);
68
- }
69
- });
70
- const logout = (options) => __awaiter(void 0, void 0, void 0, function* () {
71
- yield (authClient === null || authClient === void 0 ? void 0 : authClient.logout(options));
72
- yield authenticate();
73
- });
74
- (0, react_1.useEffect)(() => {
75
- if (!authClient && !authenticating) {
76
- authenticate();
77
- }
78
- }, [authClient, authenticating]);
79
- return {
80
- authClient,
81
- authenticated,
82
- authenticating,
83
- identity,
84
- login,
85
- logout,
86
- authenticate,
87
- loginLoading,
88
- loginError,
89
- };
90
- };
91
- const { useQueryCall, useMethodField, useMethodFields, useUpdateCall } = (0, hooks_1.getActorHooks)(callMethod, methodFields);
92
- return {
93
- useMethodFields,
94
- useMethodField,
95
- useActorStore,
96
- useAuthStore,
97
- useQueryCall,
98
- useUpdateCall,
99
- useAuthClient,
100
- };
101
- };
102
- exports.createReActor = createReActor;
package/dist/context.d.ts DELETED
@@ -1,14 +0,0 @@
1
- import React, { PropsWithChildren } from "react";
2
- import { type ReActorHooks } from "./index";
3
- import { IDL } from "@dfinity/candid";
4
- import { ActorSubclass, AgentManager, CreateReActorOptions } from "@ic-reactor/store";
5
- export type ReActorContextType<A = ActorSubclass<any>> = ReActorHooks<A>;
6
- export declare const ReActorContext: React.Context<ReActorContextType<any> | null>;
7
- export declare const useReActor: <A = any>() => ReActorContextType<A>;
8
- interface ReActorProviderProps extends PropsWithChildren, Omit<CreateReActorOptions, "idlFactory"> {
9
- agentManager?: AgentManager;
10
- idlFactory?: IDL.InterfaceFactory;
11
- loadingComponent?: React.ReactNode;
12
- }
13
- export declare const ReActorProvider: React.FC<ReActorProviderProps>;
14
- export {};
package/dist/context.js DELETED
@@ -1,117 +0,0 @@
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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
- return new (P || (P = Promise))(function (resolve, reject) {
28
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
- step((generator = generator.apply(thisArg, _arguments || [])).next());
32
- });
33
- };
34
- var __rest = (this && this.__rest) || function (s, e) {
35
- var t = {};
36
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
37
- t[p] = s[p];
38
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
39
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
40
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
41
- t[p[i]] = s[p[i]];
42
- }
43
- return t;
44
- };
45
- Object.defineProperty(exports, "__esModule", { value: true });
46
- exports.ReActorProvider = exports.useReActor = exports.ReActorContext = void 0;
47
- const react_1 = __importStar(require("react"));
48
- const index_1 = require("./index");
49
- const store_1 = require("@ic-reactor/store");
50
- exports.ReActorContext = (0, react_1.createContext)(null);
51
- const useReActor = () => {
52
- const context = (0, react_1.useContext)(exports.ReActorContext);
53
- if (!context) {
54
- throw new Error("useReActor must be used within a ReActorProvider");
55
- }
56
- return context;
57
- };
58
- exports.useReActor = useReActor;
59
- const ReActorProvider = (_a) => {
60
- var { children, canisterId, loadingComponent = react_1.default.createElement("div", null, "Loading...") } = _a, config = __rest(_a, ["children", "canisterId", "loadingComponent"]);
61
- const agentManager = (0, react_1.useRef)(config.agentManager || (0, store_1.createAgentManager)(config));
62
- const [didJs, setDidJS] = (0, react_1.useState)();
63
- const fetchDidJs = (0, react_1.useCallback)(() => __awaiter(void 0, void 0, void 0, function* () {
64
- if (!canisterId) {
65
- throw new Error("canisterId is required");
66
- }
67
- const agent = agentManager.current.getAgent();
68
- (0, store_1.getDidJsFromMetadata)(agent, canisterId).then((idlFactory) => __awaiter(void 0, void 0, void 0, function* () {
69
- if (!idlFactory) {
70
- try {
71
- idlFactory = yield (0, store_1.getDidJsFromTmpHack)(agent, canisterId);
72
- }
73
- catch (err) {
74
- if (/no query method/.test(err)) {
75
- console.warn(err);
76
- idlFactory = undefined;
77
- }
78
- else {
79
- throw err;
80
- }
81
- }
82
- if (!idlFactory) {
83
- console.warn("No query method found for canister", canisterId);
84
- }
85
- }
86
- setDidJS(idlFactory);
87
- }));
88
- return didJs;
89
- }), [canisterId]);
90
- (0, react_1.useEffect)(() => {
91
- const { idlFactory } = config;
92
- if (idlFactory) {
93
- setDidJS({ idlFactory });
94
- return;
95
- }
96
- fetchDidJs();
97
- }, [fetchDidJs, config.idlFactory]);
98
- const hooks = (0, react_1.useMemo)(() => {
99
- if (!didJs) {
100
- return null;
101
- }
102
- try {
103
- return (0, index_1.createReActor)({
104
- idlFactory: didJs.idlFactory,
105
- agentManager: agentManager.current,
106
- canisterId,
107
- withDevtools: config.withDevtools,
108
- });
109
- }
110
- catch (err) {
111
- console.error(err);
112
- return null;
113
- }
114
- }, [canisterId, didJs]);
115
- return (react_1.default.createElement(exports.ReActorContext.Provider, { value: hooks }, hooks === null ? loadingComponent : children));
116
- };
117
- exports.ReActorProvider = ReActorProvider;
@@ -1,6 +0,0 @@
1
- import type { ActorSubclass } from "@ic-reactor/store";
2
- import { getAuthHooks } from "./auth";
3
- import { getActorHooks } from "./actor";
4
- export type ReActorHooks<A extends ActorSubclass<any>> = ReturnType<typeof getActorHooks<A>> & ReturnType<typeof getAuthHooks>;
5
- export { getActorHooks } from "./actor";
6
- export { getAuthHooks } from "./auth";
@@ -1,7 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getAuthHooks = exports.getActorHooks = void 0;
4
- var actor_1 = require("./actor");
5
- Object.defineProperty(exports, "getActorHooks", { enumerable: true, get: function () { return actor_1.getActorHooks; } });
6
- var auth_1 = require("./auth");
7
- Object.defineProperty(exports, "getAuthHooks", { enumerable: true, get: function () { return auth_1.getAuthHooks; } });
package/dist/hooks.d.ts DELETED
@@ -1,20 +0,0 @@
1
- import type { CallActorMethod, ExtractActorMethodArgs, ActorMethodField } from "@ic-reactor/store";
2
- import type { ReActorUseQueryArgs, ReActorUseUpdateArgs } from "./types";
3
- export declare const getActorHooks: <A extends unknown>(callMethod: CallActorMethod<A>, methodFields: ActorMethodField<A>[]) => {
4
- useQueryCall: <M extends keyof A>({ autoRefresh, refreshInterval, disableInitialCall, ...rest }: ReActorUseQueryArgs<A, M>) => {
5
- data: import("@ic-reactor/store").ExtractActorMethodReturnType<A[M]> | undefined;
6
- error: Error | undefined;
7
- loading: boolean;
8
- field: ActorMethodField<A> | undefined;
9
- call: (replaceArgs?: ExtractActorMethodArgs<A[M]> | undefined) => Promise<import("@ic-reactor/store").ExtractActorMethodReturnType<A[M]> | undefined>;
10
- };
11
- useUpdateCall: <M_1 extends keyof A>(args: ReActorUseUpdateArgs<A, M_1>) => {
12
- data: import("@ic-reactor/store").ExtractActorMethodReturnType<A[M_1]> | undefined;
13
- error: Error | undefined;
14
- loading: boolean;
15
- call: (replaceArgs?: ExtractActorMethodArgs<A[M_1]> | undefined) => Promise<import("@ic-reactor/store").ExtractActorMethodReturnType<A[M_1]> | undefined>;
16
- field: ActorMethodField<A> | undefined;
17
- };
18
- useMethodField: (functionName: keyof A & string) => ActorMethodField<A> | undefined;
19
- useMethodFields: () => ActorMethodField<A>[];
20
- };
package/dist/hooks.js DELETED
@@ -1,94 +0,0 @@
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
- var __rest = (this && this.__rest) || function (s, e) {
12
- var t = {};
13
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
14
- t[p] = s[p];
15
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
16
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
17
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
18
- t[p[i]] = s[p[i]];
19
- }
20
- return t;
21
- };
22
- Object.defineProperty(exports, "__esModule", { value: true });
23
- exports.getActorHooks = void 0;
24
- const react_1 = require("react");
25
- const getActorHooks = (callMethod, methodFields) => {
26
- const useMethodFields = () => {
27
- return methodFields;
28
- };
29
- const useMethodField = (functionName) => {
30
- const methodFields = useMethodFields();
31
- const field = (0, react_1.useMemo)(() => {
32
- return methodFields.find((f) => f.functionName === functionName);
33
- }, [methodFields, functionName]);
34
- return field;
35
- };
36
- const useReActorCall = ({ onError, onSuccess, onLoading, args = [], functionName, }) => {
37
- const [state, setState] = (0, react_1.useState)({
38
- data: undefined,
39
- error: undefined,
40
- loading: false,
41
- });
42
- const call = (0, react_1.useCallback)((replaceArgs) => __awaiter(void 0, void 0, void 0, function* () {
43
- onLoading === null || onLoading === void 0 ? void 0 : onLoading(true);
44
- onError === null || onError === void 0 ? void 0 : onError(undefined);
45
- setState((prevState) => (Object.assign(Object.assign({}, prevState), { loading: true, error: undefined })));
46
- try {
47
- const data = yield callMethod(functionName, ...(replaceArgs !== null && replaceArgs !== void 0 ? replaceArgs : args));
48
- onLoading === null || onLoading === void 0 ? void 0 : onLoading(false);
49
- onSuccess === null || onSuccess === void 0 ? void 0 : onSuccess(data);
50
- setState((prevState) => (Object.assign(Object.assign({}, prevState), { data, loading: false })));
51
- return data;
52
- }
53
- catch (error) {
54
- console.error("Error in call:", error);
55
- onError === null || onError === void 0 ? void 0 : onError(error);
56
- onLoading === null || onLoading === void 0 ? void 0 : onLoading(false);
57
- setState((prevState) => (Object.assign(Object.assign({}, prevState), { error: error, loading: false })));
58
- }
59
- }), [args, functionName, onError, onSuccess, onLoading]);
60
- const field = useMethodField(functionName);
61
- return Object.assign({ call, field }, state);
62
- };
63
- const useQueryCall = (_a) => {
64
- var { autoRefresh, refreshInterval = 5000, disableInitialCall } = _a, rest = __rest(_a, ["autoRefresh", "refreshInterval", "disableInitialCall"]);
65
- const _b = useReActorCall(rest), { call } = _b, state = __rest(_b, ["call"]);
66
- let intervalId = (0, react_1.useRef)(undefined);
67
- (0, react_1.useEffect)(() => {
68
- // Auto-refresh logic
69
- if (autoRefresh) {
70
- intervalId.current = setInterval(() => {
71
- call();
72
- }, refreshInterval);
73
- }
74
- // Initial call logic
75
- if (!disableInitialCall) {
76
- call();
77
- }
78
- return () => {
79
- clearInterval(intervalId.current);
80
- };
81
- }, [disableInitialCall, autoRefresh, refreshInterval]);
82
- return Object.assign({ call }, state);
83
- };
84
- const useUpdateCall = (args) => {
85
- return useReActorCall(args);
86
- };
87
- return {
88
- useQueryCall,
89
- useUpdateCall,
90
- useMethodField,
91
- useMethodFields,
92
- };
93
- };
94
- exports.getActorHooks = getActorHooks;