@dynamic-labs/sdk-react-core 3.0.0-alpha.64 → 3.0.0-alpha.65

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 (30) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/package.cjs +1 -1
  3. package/package.js +1 -1
  4. package/package.json +11 -11
  5. package/src/lib/components/NetworkPicker/NetworkPicker.cjs +4 -1
  6. package/src/lib/components/NetworkPicker/NetworkPicker.js +4 -1
  7. package/src/lib/config/ApiEndpoint.cjs +6 -20
  8. package/src/lib/config/ApiEndpoint.d.ts +1 -2
  9. package/src/lib/config/ApiEndpoint.js +6 -20
  10. package/src/lib/store/state/networkConfigurations/networkConfigurations.cjs +2 -1
  11. package/src/lib/store/state/networkConfigurations/networkConfigurations.js +2 -1
  12. package/src/lib/utils/hooks/useFetchNonce/useFetchNonce.cjs +1 -0
  13. package/src/lib/utils/hooks/useFetchNonce/useFetchNonce.js +1 -0
  14. package/src/lib/utils/hooks/usePromise/usePromise.cjs +34 -60
  15. package/src/lib/utils/hooks/usePromise/usePromise.d.ts +3 -10
  16. package/src/lib/utils/hooks/usePromise/usePromise.js +35 -61
  17. package/src/lib/utils/hooks/usePromise/usePromise.types.d.ts +24 -7
  18. package/src/lib/utils/hooks/usePromise/utils/resolveFetcher/resolveFetcher.cjs +1 -0
  19. package/src/lib/utils/hooks/usePromise/utils/resolveFetcher/resolveFetcher.d.ts +1 -1
  20. package/src/lib/utils/hooks/usePromise/utils/resolveFetcher/resolveFetcher.js +1 -0
  21. package/src/lib/utils/hooks/useWalletItemActions/useWalletItemActions.cjs +0 -1
  22. package/src/lib/utils/hooks/useWalletItemActions/useWalletItemActions.js +0 -1
  23. package/src/lib/views/MfaVerificationView/MfaVerificationView.cjs +1 -0
  24. package/src/lib/views/MfaVerificationView/MfaVerificationView.js +1 -0
  25. package/src/lib/views/TransactionConfirmationView/TransactionConfirmationView.cjs +1 -0
  26. package/src/lib/views/TransactionConfirmationView/TransactionConfirmationView.js +1 -0
  27. package/src/lib/widgets/DynamicWidget/components/ActiveWalletInformation/ActiveWalletInformation.cjs +1 -1
  28. package/src/lib/widgets/DynamicWidget/components/ActiveWalletInformation/ActiveWalletInformation.js +1 -1
  29. package/src/lib/utils/hooks/usePromise/utils/createReducer/createReducer.cjs +0 -19
  30. package/src/lib/utils/hooks/usePromise/utils/createReducer/createReducer.js +0 -15
package/CHANGELOG.md CHANGED
@@ -1,4 +1,11 @@
1
1
 
2
+ ## [3.0.0-alpha.65](https://github.com/dynamic-labs/DynamicAuth/compare/v3.0.0-alpha.64...v3.0.0-alpha.65) (2024-09-11)
3
+
4
+
5
+ ### Bug Fixes
6
+
7
+ * gracefully handle errors when trying to find solana tx destination ([#6847](https://github.com/dynamic-labs/DynamicAuth/issues/6847)) ([19359ad](https://github.com/dynamic-labs/DynamicAuth/commit/19359ad40b16af0edb822d1fc6643fecdbc89adf))
8
+
2
9
  ## [3.0.0-alpha.64](https://github.com/dynamic-labs/DynamicAuth/compare/v3.0.0-alpha.63...v3.0.0-alpha.64) (2024-09-10)
3
10
 
4
11
 
package/package.cjs CHANGED
@@ -3,7 +3,7 @@
3
3
 
4
4
  Object.defineProperty(exports, '__esModule', { value: true });
5
5
 
6
- var version = "3.0.0-alpha.64";
6
+ var version = "3.0.0-alpha.65";
7
7
  var dependencies = {
8
8
  "@dynamic-labs/sdk-api-core": "0.0.526",
9
9
  "@hcaptcha/react-hcaptcha": "1.4.4",
package/package.js CHANGED
@@ -1,5 +1,5 @@
1
1
  'use client'
2
- var version = "3.0.0-alpha.64";
2
+ var version = "3.0.0-alpha.65";
3
3
  var dependencies = {
4
4
  "@dynamic-labs/sdk-api-core": "0.0.526",
5
5
  "@hcaptcha/react-hcaptcha": "1.4.4",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dynamic-labs/sdk-react-core",
3
- "version": "3.0.0-alpha.64",
3
+ "version": "3.0.0-alpha.65",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/dynamic-labs/dynamic-auth.git",
@@ -17,16 +17,16 @@
17
17
  "react-i18next": "13.5.0",
18
18
  "yup": "0.32.11",
19
19
  "react-international-phone": "4.2.5",
20
- "@dynamic-labs/iconic": "3.0.0-alpha.64",
21
- "@dynamic-labs/logger": "3.0.0-alpha.64",
22
- "@dynamic-labs/message-transport": "3.0.0-alpha.64",
23
- "@dynamic-labs/multi-wallet": "3.0.0-alpha.64",
24
- "@dynamic-labs/rpc-providers": "3.0.0-alpha.64",
25
- "@dynamic-labs/store": "3.0.0-alpha.64",
26
- "@dynamic-labs/types": "3.0.0-alpha.64",
27
- "@dynamic-labs/utils": "3.0.0-alpha.64",
28
- "@dynamic-labs/wallet-book": "3.0.0-alpha.64",
29
- "@dynamic-labs/wallet-connector-core": "3.0.0-alpha.64",
20
+ "@dynamic-labs/iconic": "3.0.0-alpha.65",
21
+ "@dynamic-labs/logger": "3.0.0-alpha.65",
22
+ "@dynamic-labs/message-transport": "3.0.0-alpha.65",
23
+ "@dynamic-labs/multi-wallet": "3.0.0-alpha.65",
24
+ "@dynamic-labs/rpc-providers": "3.0.0-alpha.65",
25
+ "@dynamic-labs/store": "3.0.0-alpha.65",
26
+ "@dynamic-labs/types": "3.0.0-alpha.65",
27
+ "@dynamic-labs/utils": "3.0.0-alpha.65",
28
+ "@dynamic-labs/wallet-book": "3.0.0-alpha.65",
29
+ "@dynamic-labs/wallet-connector-core": "3.0.0-alpha.65",
30
30
  "eventemitter3": "5.0.1"
31
31
  },
32
32
  "devDependencies": {
@@ -105,7 +105,10 @@ const NetworkPicker = ({ activeClassName = '', buttonClassName = '', checkboxCla
105
105
  const { loadingNetwork } = useInternalDynamicContext.useInternalDynamicContext();
106
106
  const { data: supportedWalletNetworks } = usePromise.usePromise(() => walletConnectorCore.isWalletConnectConnector(connector)
107
107
  ? connector.getSupportedNetworks()
108
- : Promise.resolve(evmNetworks.map(({ networkId }) => `${networkId}`)), { deps: [connector, evmNetworks, isNetworkPickerOpen] });
108
+ : Promise.resolve(evmNetworks.map(({ networkId }) => `${networkId}`)), {
109
+ deps: [connector, evmNetworks, isNetworkPickerOpen],
110
+ initialData: undefined,
111
+ });
109
112
  const shouldAllowOpenDropdown = isNetworkUnsupported.isNetworkUnsupported(currentNetwork, evmNetworks) ||
110
113
  (evmNetworks === null || evmNetworks === void 0 ? void 0 : evmNetworks.length) > 1;
111
114
  // Ref to anchor popper to
@@ -101,7 +101,10 @@ const NetworkPicker = ({ activeClassName = '', buttonClassName = '', checkboxCla
101
101
  const { loadingNetwork } = useInternalDynamicContext();
102
102
  const { data: supportedWalletNetworks } = usePromise(() => isWalletConnectConnector(connector)
103
103
  ? connector.getSupportedNetworks()
104
- : Promise.resolve(evmNetworks.map(({ networkId }) => `${networkId}`)), { deps: [connector, evmNetworks, isNetworkPickerOpen] });
104
+ : Promise.resolve(evmNetworks.map(({ networkId }) => `${networkId}`)), {
105
+ deps: [connector, evmNetworks, isNetworkPickerOpen],
106
+ initialData: undefined,
107
+ });
105
108
  const shouldAllowOpenDropdown = isNetworkUnsupported(currentNetwork, evmNetworks) ||
106
109
  (evmNetworks === null || evmNetworks === void 0 ? void 0 : evmNetworks.length) > 1;
107
110
  // Ref to anchor popper to
@@ -7,35 +7,21 @@ var sdkApiCore = require('@dynamic-labs/sdk-api-core');
7
7
  class ApiEndpoint {
8
8
  }
9
9
  ApiEndpoint.getBaseUrl = () => {
10
- if (!ApiEndpoint.__defined__) {
10
+ if (!ApiEndpoint.__baseUrl__) {
11
11
  throw new Error('ApiEndpoint Base URL has not been initialized');
12
12
  }
13
13
  return ApiEndpoint.__baseUrl__;
14
14
  };
15
15
  ApiEndpoint.setBaseUrl = (baseUrlInput) => {
16
- if (!ApiEndpoint.__defined__) {
17
- if (!baseUrlInput) {
18
- /**
19
- * If the baseUrl is not provided, use the default baseUrl from the sdk-api package
20
- */
21
- ApiEndpoint.__baseUrl__ = new sdkApiCore.Configuration().basePath;
22
- }
23
- else {
24
- ApiEndpoint.__baseUrl__ = baseUrlInput;
25
- }
26
- ApiEndpoint.__defined__ = true;
27
- }
28
- else if (!baseUrlInput && ApiEndpoint.__defined__) {
16
+ if (!baseUrlInput) {
29
17
  /**
30
- * If for some reason (usually in local development), the setBaseUrl is called multiple times with undefined
31
- * And we already have it defined, let's just assume it's a no-op
18
+ * If the baseUrl is not provided, use the default baseUrl from the sdk-api package
32
19
  */
33
- return;
20
+ ApiEndpoint.__baseUrl__ = new sdkApiCore.Configuration().basePath;
34
21
  }
35
- else if (ApiEndpoint.__baseUrl__ !== baseUrlInput) {
36
- throw new Error(`ApiEndpoint baseUrl is already set to ${ApiEndpoint.__baseUrl__}, cannot change it to ${baseUrlInput}`);
22
+ else {
23
+ ApiEndpoint.__baseUrl__ = baseUrlInput;
37
24
  }
38
- Object.freeze(ApiEndpoint);
39
25
  };
40
26
 
41
27
  module.exports = ApiEndpoint;
@@ -1,7 +1,6 @@
1
1
  declare class ApiEndpoint {
2
2
  private static __baseUrl__;
3
- private static __defined__;
4
- static getBaseUrl: () => string | undefined;
3
+ static getBaseUrl: () => string;
5
4
  static setBaseUrl: (baseUrlInput?: string) => void;
6
5
  }
7
6
  export default ApiEndpoint;
@@ -5,35 +5,21 @@ import { Configuration } from '@dynamic-labs/sdk-api-core';
5
5
  class ApiEndpoint {
6
6
  }
7
7
  ApiEndpoint.getBaseUrl = () => {
8
- if (!ApiEndpoint.__defined__) {
8
+ if (!ApiEndpoint.__baseUrl__) {
9
9
  throw new Error('ApiEndpoint Base URL has not been initialized');
10
10
  }
11
11
  return ApiEndpoint.__baseUrl__;
12
12
  };
13
13
  ApiEndpoint.setBaseUrl = (baseUrlInput) => {
14
- if (!ApiEndpoint.__defined__) {
15
- if (!baseUrlInput) {
16
- /**
17
- * If the baseUrl is not provided, use the default baseUrl from the sdk-api package
18
- */
19
- ApiEndpoint.__baseUrl__ = new Configuration().basePath;
20
- }
21
- else {
22
- ApiEndpoint.__baseUrl__ = baseUrlInput;
23
- }
24
- ApiEndpoint.__defined__ = true;
25
- }
26
- else if (!baseUrlInput && ApiEndpoint.__defined__) {
14
+ if (!baseUrlInput) {
27
15
  /**
28
- * If for some reason (usually in local development), the setBaseUrl is called multiple times with undefined
29
- * And we already have it defined, let's just assume it's a no-op
16
+ * If the baseUrl is not provided, use the default baseUrl from the sdk-api package
30
17
  */
31
- return;
18
+ ApiEndpoint.__baseUrl__ = new Configuration().basePath;
32
19
  }
33
- else if (ApiEndpoint.__baseUrl__ !== baseUrlInput) {
34
- throw new Error(`ApiEndpoint baseUrl is already set to ${ApiEndpoint.__baseUrl__}, cannot change it to ${baseUrlInput}`);
20
+ else {
21
+ ApiEndpoint.__baseUrl__ = baseUrlInput;
35
22
  }
36
- Object.freeze(ApiEndpoint);
37
23
  };
38
24
 
39
25
  export { ApiEndpoint as default };
@@ -152,11 +152,12 @@ const useNetworkConfigurations = ({ environmentId, projectSettings, evmNetworksO
152
152
  }), {
153
153
  deps: [environmentId, projectSettings, evmNetworksOverrides],
154
154
  enabled: Boolean(projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.networks),
155
+ initialData: undefined,
155
156
  onResolve: (networkConfigurations) => {
156
157
  const expiry = new Date().getTime() + 60000 * 5;
157
158
  setNetworkConfigurations({
158
159
  expiresAt: expiry,
159
- networkConfigurations,
160
+ networkConfigurations: networkConfigurations,
160
161
  });
161
162
  },
162
163
  });
@@ -148,11 +148,12 @@ const useNetworkConfigurations = ({ environmentId, projectSettings, evmNetworksO
148
148
  }), {
149
149
  deps: [environmentId, projectSettings, evmNetworksOverrides],
150
150
  enabled: Boolean(projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.networks),
151
+ initialData: undefined,
151
152
  onResolve: (networkConfigurations) => {
152
153
  const expiry = new Date().getTime() + 60000 * 5;
153
154
  setNetworkConfigurations({
154
155
  expiresAt: expiry,
155
- networkConfigurations,
156
+ networkConfigurations: networkConfigurations,
156
157
  });
157
158
  },
158
159
  });
@@ -48,6 +48,7 @@ const useFetchNonce = (environmentId, maxRetries = 2) => {
48
48
  }), {
49
49
  deps: [environmentId, nonceExists],
50
50
  enabled: !nonceExists,
51
+ initialData: undefined,
51
52
  onResolve: setLsNonce,
52
53
  retries: maxRetries,
53
54
  });
@@ -44,6 +44,7 @@ const useFetchNonce = (environmentId, maxRetries = 2) => {
44
44
  }), {
45
45
  deps: [environmentId, nonceExists],
46
46
  enabled: !nonceExists,
47
+ initialData: undefined,
47
48
  onResolve: setLsNonce,
48
49
  retries: maxRetries,
49
50
  });
@@ -3,36 +3,17 @@
3
3
 
4
4
  Object.defineProperty(exports, '__esModule', { value: true });
5
5
 
6
+ var _tslib = require('../../../../../_virtual/_tslib.cjs');
6
7
  var React = require('react');
7
- require('@dynamic-labs/sdk-api-core');
8
8
  var logger = require('../../../shared/logger.cjs');
9
- require('@dynamic-labs/iconic');
10
- require('@dynamic-labs/wallet-connector-core');
11
- require('react/jsx-runtime');
12
- require('../../../context/ViewContext/ViewContext.cjs');
13
- require('@dynamic-labs/wallet-book');
14
- require('../../constants/colors.cjs');
15
- require('../../constants/values.cjs');
16
- require('../../../shared/utils/classes/storage/localStorage.cjs');
17
- require('../../../store/state/loadingAndLifecycle.cjs');
18
- require('@dynamic-labs/utils');
19
- require('../../../shared/consts/index.cjs');
20
9
  var resolveFetcher = require('./utils/resolveFetcher/resolveFetcher.cjs');
21
- var createReducer = require('./utils/createReducer/createReducer.cjs');
22
10
 
23
11
  /**
24
12
  * Custom hook for handling promises and fetching data.
25
13
  * @template T - The type of the data returned by the promise.
26
14
  * @template E - The type of the error thrown by the promise.
27
- * @param {() => T | Promise<T>} fetcher - A function that returns the data or a promise that resolves to the data.
28
- * @param {UsePromiseOptions<T, E>} [options={}] - Options for the hook.
29
- * @param {number} [options.retries] - The number of times to retry the fetch in case of failure.
30
- * @param {T} [options.initialData] - The initial data the hook will use until the promise is resolved.
31
- * @param {DependencyList} [options.deps=[]] - An array of dependencies for the hook.
32
- * @param {boolean} [options.enabled] - Flag indicating whether the fetch should be enabled or not.
33
- * @param {(data: T) => void} [options.onResolve] - Callback to be called when the fetch is resolved successfully.
34
- * @param {(error: E) => void} [options.onReject] - Callback to be called when the fetch is rejected with an error.
35
- * @returns {PromiseState<T, E>} - The state object containing the data, error, and loading status.
15
+ * @returns {PromiseState<T, E>} - The state object containing the data, error, loading status
16
+ * and a callback to manually retrigger the promise.
36
17
  * @example
37
18
  * // Example usage with a simple fetcher function
38
19
  * const fetcher = fetch('https://api.example.com/data');
@@ -51,56 +32,49 @@ var createReducer = require('./utils/createReducer/createReducer.cjs');
51
32
  * return <div>Data: {data}</div>;
52
33
  * };
53
34
  */
54
- const usePromise = (fetcher, options) => {
35
+ const usePromise = (
36
+ /** A function that returns the data or a promise that resolves to the data */
37
+ fetcher,
38
+ /** Options for the hook */
39
+ options) => {
55
40
  const lastCallTimestamp = React.useRef(new Date().getTime());
56
- const { deps = [], initialData = undefined, enabled = true, retries = 0, onReject = () => { }, onResolve = () => { }, } = options || {};
57
- const [state, dispatch] = React.useReducer(createReducer.createReducer(), {
58
- data: initialData,
59
- isLoading: enabled,
60
- });
61
- const callback = React.useCallback(() => {
41
+ const { deps = [], initialData = undefined, enabled = true, retries = 0, onBeforeFetch = () => { }, onReject = () => { }, onResolve = () => { }, } = options || {};
42
+ const [data, setData] = React.useState(initialData);
43
+ const [isLoading, setIsLoading] = React.useState(enabled);
44
+ const [error, setError] = React.useState(undefined);
45
+ const trigger = React.useCallback(() => _tslib.__awaiter(void 0, void 0, void 0, function* () {
62
46
  const callTimestamp = new Date().getTime();
63
47
  const diffFromLastCall = callTimestamp - lastCallTimestamp.current;
64
48
  if (diffFromLastCall < 5) {
65
- logger.logger.debug('usePromise: Fetcher function was called too soon. Please make sure you are not calling the fetcher function inside a loop or a synchronous function.', deps);
49
+ logger.logger.warn('usePromise: Fetcher function was called in very quick succession. Please make sure the fetcher function is not synchronous and that you are not calling it inside a loop.', deps);
66
50
  }
67
51
  lastCallTimestamp.current = callTimestamp;
68
- if (!state.isLoading) {
69
- dispatch({
70
- payload: true,
71
- type: 'SET_LOADING',
72
- });
73
- }
74
- resolveFetcher.resolveFetcher(fetcher, { retries }, (error, data) => {
52
+ setIsLoading(true);
53
+ onBeforeFetch();
54
+ return resolveFetcher.resolveFetcher(fetcher, { retries }, (resultError, resultData) => {
75
55
  if (callTimestamp !== lastCallTimestamp.current)
76
56
  return;
77
- if (error) {
78
- logger.logger.error(error);
79
- dispatch({
80
- payload: error,
81
- type: 'SET_ERROR',
82
- });
83
- onReject === null || onReject === void 0 ? void 0 : onReject(error);
57
+ if (resultError) {
58
+ logger.logger.error(resultError);
59
+ setError(resultError);
60
+ onReject === null || onReject === void 0 ? void 0 : onReject(resultError);
84
61
  return;
85
62
  }
86
- dispatch({
87
- payload: data,
88
- type: 'SET_DATA',
89
- });
90
- onResolve === null || onResolve === void 0 ? void 0 : onResolve(data);
91
- dispatch({
92
- payload: false,
93
- type: 'SET_LOADING',
94
- });
95
- });
63
+ setData(resultData);
64
+ onResolve === null || onResolve === void 0 ? void 0 : onResolve(resultData);
65
+ }).finally(() => setIsLoading(false));
96
66
  // eslint-disable-next-line react-hooks/exhaustive-deps
97
- }, deps);
67
+ }), deps);
98
68
  React.useEffect(() => {
99
- if (enabled) {
100
- callback();
101
- }
102
- }, [callback, enabled]);
103
- return state;
69
+ if (enabled)
70
+ trigger();
71
+ }, [trigger, enabled]);
72
+ return React.useMemo(() => ({
73
+ data: data,
74
+ error,
75
+ isLoading,
76
+ retrigger: trigger,
77
+ }), [data, error, isLoading, trigger]);
104
78
  };
105
79
 
106
80
  exports.usePromise = usePromise;
@@ -1,17 +1,10 @@
1
- import { UsePromiseOptions, PromiseState } from './usePromise.types';
1
+ import { PromiseState, UsePromiseOptions } from './usePromise.types';
2
2
  /**
3
3
  * Custom hook for handling promises and fetching data.
4
4
  * @template T - The type of the data returned by the promise.
5
5
  * @template E - The type of the error thrown by the promise.
6
- * @param {() => T | Promise<T>} fetcher - A function that returns the data or a promise that resolves to the data.
7
- * @param {UsePromiseOptions<T, E>} [options={}] - Options for the hook.
8
- * @param {number} [options.retries] - The number of times to retry the fetch in case of failure.
9
- * @param {T} [options.initialData] - The initial data the hook will use until the promise is resolved.
10
- * @param {DependencyList} [options.deps=[]] - An array of dependencies for the hook.
11
- * @param {boolean} [options.enabled] - Flag indicating whether the fetch should be enabled or not.
12
- * @param {(data: T) => void} [options.onResolve] - Callback to be called when the fetch is resolved successfully.
13
- * @param {(error: E) => void} [options.onReject] - Callback to be called when the fetch is rejected with an error.
14
- * @returns {PromiseState<T, E>} - The state object containing the data, error, and loading status.
6
+ * @returns {PromiseState<T, E>} - The state object containing the data, error, loading status
7
+ * and a callback to manually retrigger the promise.
15
8
  * @example
16
9
  * // Example usage with a simple fetcher function
17
10
  * const fetcher = fetch('https://api.example.com/data');
@@ -1,34 +1,15 @@
1
1
  'use client'
2
- import { useRef, useReducer, useCallback, useEffect } from 'react';
3
- import '@dynamic-labs/sdk-api-core';
2
+ import { __awaiter } from '../../../../../_virtual/_tslib.js';
3
+ import { useRef, useState, useCallback, useEffect, useMemo } from 'react';
4
4
  import { logger } from '../../../shared/logger.js';
5
- import '@dynamic-labs/iconic';
6
- import '@dynamic-labs/wallet-connector-core';
7
- import 'react/jsx-runtime';
8
- import '../../../context/ViewContext/ViewContext.js';
9
- import '@dynamic-labs/wallet-book';
10
- import '../../constants/colors.js';
11
- import '../../constants/values.js';
12
- import '../../../shared/utils/classes/storage/localStorage.js';
13
- import '../../../store/state/loadingAndLifecycle.js';
14
- import '@dynamic-labs/utils';
15
- import '../../../shared/consts/index.js';
16
5
  import { resolveFetcher } from './utils/resolveFetcher/resolveFetcher.js';
17
- import { createReducer } from './utils/createReducer/createReducer.js';
18
6
 
19
7
  /**
20
8
  * Custom hook for handling promises and fetching data.
21
9
  * @template T - The type of the data returned by the promise.
22
10
  * @template E - The type of the error thrown by the promise.
23
- * @param {() => T | Promise<T>} fetcher - A function that returns the data or a promise that resolves to the data.
24
- * @param {UsePromiseOptions<T, E>} [options={}] - Options for the hook.
25
- * @param {number} [options.retries] - The number of times to retry the fetch in case of failure.
26
- * @param {T} [options.initialData] - The initial data the hook will use until the promise is resolved.
27
- * @param {DependencyList} [options.deps=[]] - An array of dependencies for the hook.
28
- * @param {boolean} [options.enabled] - Flag indicating whether the fetch should be enabled or not.
29
- * @param {(data: T) => void} [options.onResolve] - Callback to be called when the fetch is resolved successfully.
30
- * @param {(error: E) => void} [options.onReject] - Callback to be called when the fetch is rejected with an error.
31
- * @returns {PromiseState<T, E>} - The state object containing the data, error, and loading status.
11
+ * @returns {PromiseState<T, E>} - The state object containing the data, error, loading status
12
+ * and a callback to manually retrigger the promise.
32
13
  * @example
33
14
  * // Example usage with a simple fetcher function
34
15
  * const fetcher = fetch('https://api.example.com/data');
@@ -47,56 +28,49 @@ import { createReducer } from './utils/createReducer/createReducer.js';
47
28
  * return <div>Data: {data}</div>;
48
29
  * };
49
30
  */
50
- const usePromise = (fetcher, options) => {
31
+ const usePromise = (
32
+ /** A function that returns the data or a promise that resolves to the data */
33
+ fetcher,
34
+ /** Options for the hook */
35
+ options) => {
51
36
  const lastCallTimestamp = useRef(new Date().getTime());
52
- const { deps = [], initialData = undefined, enabled = true, retries = 0, onReject = () => { }, onResolve = () => { }, } = options || {};
53
- const [state, dispatch] = useReducer(createReducer(), {
54
- data: initialData,
55
- isLoading: enabled,
56
- });
57
- const callback = useCallback(() => {
37
+ const { deps = [], initialData = undefined, enabled = true, retries = 0, onBeforeFetch = () => { }, onReject = () => { }, onResolve = () => { }, } = options || {};
38
+ const [data, setData] = useState(initialData);
39
+ const [isLoading, setIsLoading] = useState(enabled);
40
+ const [error, setError] = useState(undefined);
41
+ const trigger = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
58
42
  const callTimestamp = new Date().getTime();
59
43
  const diffFromLastCall = callTimestamp - lastCallTimestamp.current;
60
44
  if (diffFromLastCall < 5) {
61
- logger.debug('usePromise: Fetcher function was called too soon. Please make sure you are not calling the fetcher function inside a loop or a synchronous function.', deps);
45
+ logger.warn('usePromise: Fetcher function was called in very quick succession. Please make sure the fetcher function is not synchronous and that you are not calling it inside a loop.', deps);
62
46
  }
63
47
  lastCallTimestamp.current = callTimestamp;
64
- if (!state.isLoading) {
65
- dispatch({
66
- payload: true,
67
- type: 'SET_LOADING',
68
- });
69
- }
70
- resolveFetcher(fetcher, { retries }, (error, data) => {
48
+ setIsLoading(true);
49
+ onBeforeFetch();
50
+ return resolveFetcher(fetcher, { retries }, (resultError, resultData) => {
71
51
  if (callTimestamp !== lastCallTimestamp.current)
72
52
  return;
73
- if (error) {
74
- logger.error(error);
75
- dispatch({
76
- payload: error,
77
- type: 'SET_ERROR',
78
- });
79
- onReject === null || onReject === void 0 ? void 0 : onReject(error);
53
+ if (resultError) {
54
+ logger.error(resultError);
55
+ setError(resultError);
56
+ onReject === null || onReject === void 0 ? void 0 : onReject(resultError);
80
57
  return;
81
58
  }
82
- dispatch({
83
- payload: data,
84
- type: 'SET_DATA',
85
- });
86
- onResolve === null || onResolve === void 0 ? void 0 : onResolve(data);
87
- dispatch({
88
- payload: false,
89
- type: 'SET_LOADING',
90
- });
91
- });
59
+ setData(resultData);
60
+ onResolve === null || onResolve === void 0 ? void 0 : onResolve(resultData);
61
+ }).finally(() => setIsLoading(false));
92
62
  // eslint-disable-next-line react-hooks/exhaustive-deps
93
- }, deps);
63
+ }), deps);
94
64
  useEffect(() => {
95
- if (enabled) {
96
- callback();
97
- }
98
- }, [callback, enabled]);
99
- return state;
65
+ if (enabled)
66
+ trigger();
67
+ }, [trigger, enabled]);
68
+ return useMemo(() => ({
69
+ data: data,
70
+ error,
71
+ isLoading,
72
+ retrigger: trigger,
73
+ }), [data, error, isLoading, trigger]);
100
74
  };
101
75
 
102
76
  export { usePromise };
@@ -1,14 +1,31 @@
1
1
  import { DependencyList } from 'react';
2
2
  export type PromiseState<T, E> = {
3
- data?: T;
4
- error?: E;
3
+ data: T;
4
+ error: E | undefined;
5
5
  isLoading: boolean;
6
+ /**
7
+ * Re-fetches the value.
8
+ * @return the result. If the fetch fails, returns undefined.
9
+ */
10
+ retrigger: () => Promise<T | undefined>;
6
11
  };
7
- export type UsePromiseOptions<T, E> = {
12
+ export type UsePromiseOptions<T, E = Error> = {
13
+ /** An array of dependencies for the hook */
8
14
  deps?: DependencyList;
9
- retries?: number;
15
+ /** Flag indicating whether the fetch should be auto triggered or not */
10
16
  enabled?: boolean;
11
- initialData?: T;
12
- onResolve?: (data: T) => void;
17
+ /** Callback to be called before a batch of fetch attempts is made */
18
+ onBeforeFetch?: VoidFunction;
19
+ /** Callback to be called when the fetch is rejected with an error */
13
20
  onReject?: (error: E) => void;
14
- };
21
+ /** Callback to be called when the fetch is resolved successfully */
22
+ onResolve?: (data: T) => void;
23
+ /** The number of times to retry the fetch in case of failure */
24
+ retries?: number;
25
+ } & (undefined extends T ? {
26
+ /** The initial data the hook will use until the promise is resolved */
27
+ initialData?: T;
28
+ } : {
29
+ /** The initial data the hook will use until the promise is resolved */
30
+ initialData: T;
31
+ });
@@ -32,6 +32,7 @@ const resolveFetcher = (fetcher_1, _a, callback_1) => _tslib.__awaiter(void 0, [
32
32
  }
33
33
  }
34
34
  callback(err, data);
35
+ return data;
35
36
  });
36
37
 
37
38
  exports.resolveFetcher = resolveFetcher;
@@ -1,5 +1,5 @@
1
1
  type ResolveFetcherOptions = {
2
2
  retries?: number;
3
3
  };
4
- export declare const resolveFetcher: <E, T>(fetcher: () => T | Promise<T>, { retries }: ResolveFetcherOptions, callback: (err: E | undefined, data: T | undefined) => void) => Promise<void>;
4
+ export declare const resolveFetcher: <E, T>(fetcher: () => T | Promise<T>, { retries }: ResolveFetcherOptions, callback: (err: E | undefined, data: T | undefined) => void) => Promise<T | undefined>;
5
5
  export {};
@@ -28,6 +28,7 @@ const resolveFetcher = (fetcher_1, _a, callback_1) => __awaiter(void 0, [fetcher
28
28
  }
29
29
  }
30
30
  callback(err, data);
31
+ return data;
31
32
  });
32
33
 
33
34
  export { resolveFetcher };
@@ -177,7 +177,6 @@ const useWalletItemActions = () => {
177
177
  setShowAuthFlow(false);
178
178
  const connectedAccounts = yield walletConnector.getConnectedAccounts({
179
179
  chooseAccounts: true,
180
- forceFetch: true,
181
180
  });
182
181
  const activeAccountAlreadyLinked = linkedWallets.find((wallet) => { var _a; return wallet.address.toLowerCase() === ((_a = connectedAccounts[0]) === null || _a === void 0 ? void 0 : _a.toLowerCase()); });
183
182
  logVerboseTroubleshootingMessage.logVerboseTroubleshootingMessage('[handleAlreadyConnectedWallet]', {
@@ -173,7 +173,6 @@ const useWalletItemActions = () => {
173
173
  setShowAuthFlow(false);
174
174
  const connectedAccounts = yield walletConnector.getConnectedAccounts({
175
175
  chooseAccounts: true,
176
- forceFetch: true,
177
176
  });
178
177
  const activeAccountAlreadyLinked = linkedWallets.find((wallet) => { var _a; return wallet.address.toLowerCase() === ((_a = connectedAccounts[0]) === null || _a === void 0 ? void 0 : _a.toLowerCase()); });
179
178
  logVerboseTroubleshootingMessage('[handleAlreadyConnectedWallet]', {
@@ -107,6 +107,7 @@ const MfaVerificationView = ({ type, isInitialSetup = false, showBackButton = fa
107
107
  const { data: isValid, isLoading } = usePromise.usePromise(() => authDevice(code, type, deviceId), {
108
108
  deps: [code],
109
109
  enabled: (code === null || code === void 0 ? void 0 : code.length) === 6,
110
+ initialData: false,
110
111
  onReject: (err) => {
111
112
  if (err instanceof utils.MfaRateLimitedError) {
112
113
  setIsRateLimited(true);
@@ -103,6 +103,7 @@ const MfaVerificationView = ({ type, isInitialSetup = false, showBackButton = fa
103
103
  const { data: isValid, isLoading } = usePromise(() => authDevice(code, type, deviceId), {
104
104
  deps: [code],
105
105
  enabled: (code === null || code === void 0 ? void 0 : code.length) === 6,
106
+ initialData: false,
106
107
  onReject: (err) => {
107
108
  if (err instanceof MfaRateLimitedError) {
108
109
  setIsRateLimited(true);
@@ -129,6 +129,7 @@ const TransactionConfirmationView = ({ transaction, onError, onSuccess, mutation
129
129
  }
130
130
  return walletConnector.canSponsorTransactionGas(transaction);
131
131
  }, {
132
+ initialData: false,
132
133
  onReject: logger.logger.error,
133
134
  onResolve: (isGasSponsored) => {
134
135
  setIsGasSponsored(isGasSponsored);
@@ -125,6 +125,7 @@ const TransactionConfirmationView = ({ transaction, onError, onSuccess, mutation
125
125
  }
126
126
  return walletConnector.canSponsorTransactionGas(transaction);
127
127
  }, {
128
+ initialData: false,
128
129
  onReject: logger.error,
129
130
  onResolve: (isGasSponsored) => {
130
131
  setIsGasSponsored(isGasSponsored);
@@ -131,7 +131,7 @@ const ActiveWalletInformation = ({ isLoading = false, }) => {
131
131
  const address = primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.address;
132
132
  const nameService = useFetchNameService.useFetchNameService(address);
133
133
  const { getEOAWallet } = useSmartWallets.useSmartWallets();
134
- const { data: testnet } = usePromise.usePromise(() => _tslib.__awaiter(void 0, void 0, void 0, function* () { return Boolean(yield (primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector.isTestnet())); }), { deps: [network] });
134
+ const { data: testnet } = usePromise.usePromise(() => _tslib.__awaiter(void 0, void 0, void 0, function* () { return Boolean(yield (primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector.isTestnet())); }), { deps: [network], initialData: false });
135
135
  const exportKeysOption = helpers.getExportKeysOption(primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector, projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.providers);
136
136
  const { showAlert } = PasskeyContext.usePasskeyContext();
137
137
  const wallet = (_a = (primaryWallet && getEOAWallet(primaryWallet))) !== null && _a !== void 0 ? _a : primaryWallet;
@@ -127,7 +127,7 @@ const ActiveWalletInformation = ({ isLoading = false, }) => {
127
127
  const address = primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.address;
128
128
  const nameService = useFetchNameService(address);
129
129
  const { getEOAWallet } = useSmartWallets();
130
- const { data: testnet } = usePromise(() => __awaiter(void 0, void 0, void 0, function* () { return Boolean(yield (primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector.isTestnet())); }), { deps: [network] });
130
+ const { data: testnet } = usePromise(() => __awaiter(void 0, void 0, void 0, function* () { return Boolean(yield (primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector.isTestnet())); }), { deps: [network], initialData: false });
131
131
  const exportKeysOption = getExportKeysOption(primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector, projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.providers);
132
132
  const { showAlert } = usePasskeyContext();
133
133
  const wallet = (_a = (primaryWallet && getEOAWallet(primaryWallet))) !== null && _a !== void 0 ? _a : primaryWallet;
@@ -1,19 +0,0 @@
1
- 'use client'
2
- 'use strict';
3
-
4
- Object.defineProperty(exports, '__esModule', { value: true });
5
-
6
- const createReducer = () => (state, action) => {
7
- switch (action.type) {
8
- case 'SET_DATA':
9
- return Object.assign(Object.assign({}, state), { data: action.payload, isLoading: false });
10
- case 'SET_ERROR':
11
- return Object.assign(Object.assign({}, state), { error: action.payload, isLoading: false });
12
- case 'SET_LOADING':
13
- return Object.assign(Object.assign({}, state), { isLoading: action.payload });
14
- default:
15
- return state;
16
- }
17
- };
18
-
19
- exports.createReducer = createReducer;
@@ -1,15 +0,0 @@
1
- 'use client'
2
- const createReducer = () => (state, action) => {
3
- switch (action.type) {
4
- case 'SET_DATA':
5
- return Object.assign(Object.assign({}, state), { data: action.payload, isLoading: false });
6
- case 'SET_ERROR':
7
- return Object.assign(Object.assign({}, state), { error: action.payload, isLoading: false });
8
- case 'SET_LOADING':
9
- return Object.assign(Object.assign({}, state), { isLoading: action.payload });
10
- default:
11
- return state;
12
- }
13
- };
14
-
15
- export { createReducer };