@ahoo-wang/fetcher-react 2.6.2 → 2.6.3

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
@@ -92,6 +92,32 @@ const MyComponent = () => {
92
92
  };
93
93
  ```
94
94
 
95
+ ### useLatest Hook
96
+
97
+ The `useLatest` hook returns the latest value, useful for accessing the current value in async callbacks.
98
+
99
+ ```typescript jsx
100
+ import { useLatest } from '@ahoo-wang/fetcher-react';
101
+
102
+ const MyComponent = () => {
103
+ const [count, setCount] = useState(0);
104
+ const latestCount = useLatest(count);
105
+
106
+ const handleAsync = async () => {
107
+ await someAsyncOperation();
108
+ console.log('Latest count:', latestCount.current); // Always the latest
109
+ };
110
+
111
+ return (
112
+ <div>
113
+ <p>Count: {count}</p>
114
+ <button onClick={() => setCount(c => c + 1)}>Increment</button>
115
+ <button onClick={handleAsync}>Async Log</button>
116
+ </div>
117
+ );
118
+ };
119
+ ```
120
+
95
121
  ### useRequestId Hook
96
122
 
97
123
  The `useRequestId` hook provides request ID management for preventing race conditions in async operations.
@@ -253,6 +279,26 @@ An object containing:
253
279
  - `execute`: Function to execute a promise supplier or promise
254
280
  - `reset`: Function to reset the state to initial values
255
281
 
282
+ ### useLatest
283
+
284
+ ```typescript
285
+ function useLatest<T>(value: T): T;
286
+ ```
287
+
288
+ A React hook that returns the latest value, useful for accessing the current value in async callbacks.
289
+
290
+ **Type Parameters:**
291
+
292
+ - `T`: The type of the value
293
+
294
+ **Parameters:**
295
+
296
+ - `value`: The value to track
297
+
298
+ **Returns:**
299
+
300
+ The latest value
301
+
256
302
  ### useRequestId
257
303
 
258
304
  ```typescript
@@ -1,4 +1,5 @@
1
1
  export * from './useExecutePromise';
2
2
  export * from './usePromiseState';
3
3
  export * from './useRequestId';
4
+ export * from './useLatest';
4
5
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/core/index.ts"],"names":[],"mappings":"AAaA,cAAc,qBAAqB,CAAC;AACpC,cAAc,mBAAmB,CAAC;AAClC,cAAc,gBAAgB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/core/index.ts"],"names":[],"mappings":"AAaA,cAAc,qBAAqB,CAAC;AACpC,cAAc,mBAAmB,CAAC;AAClC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,aAAa,CAAC"}
@@ -0,0 +1,32 @@
1
+ /**
2
+ * A React hook that returns a ref containing the latest value, useful for accessing the current value in async callbacks.
3
+ *
4
+ * @template T - The type of the value
5
+ * @param value - The value to track
6
+ * @returns A ref object containing the latest value
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * import { useLatest } from '@ahoo-wang/fetcher-react';
11
+ *
12
+ * const MyComponent = () => {
13
+ * const [count, setCount] = useState(0);
14
+ * const latestCount = useLatest(count);
15
+ *
16
+ * const handleAsync = async () => {
17
+ * await someAsyncOperation();
18
+ * console.log('Latest count:', latestCount.current); // Always the latest
19
+ * };
20
+ *
21
+ * return (
22
+ * <div>
23
+ * <p>Count: {count}</p>
24
+ * <button onClick={() => setCount(c => c + 1)}>Increment</button>
25
+ * <button onClick={handleAsync}>Async Log</button>
26
+ * </div>
27
+ * );
28
+ * };
29
+ * ```
30
+ */
31
+ export declare function useLatest<T>(value: T): import('react').MutableRefObject<T>;
32
+ //# sourceMappingURL=useLatest.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useLatest.d.ts","sourceRoot":"","sources":["../../src/core/useLatest.ts"],"names":[],"mappings":"AAeA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,wBAAgB,SAAS,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,uCAIpC"}
@@ -17,6 +17,12 @@ export interface PromiseState<R, E = unknown> {
17
17
  /** The error value */
18
18
  error: E | undefined;
19
19
  }
20
+ export interface PromiseStateCallbacks<R, E = unknown> {
21
+ /** Callback invoked on success */
22
+ onSuccess?: (result: R) => void;
23
+ /** Callback invoked on error */
24
+ onError?: (error: E) => void;
25
+ }
20
26
  /**
21
27
  * Options for configuring usePromiseState behavior
22
28
  * @template R - The type of result
@@ -30,13 +36,9 @@ export interface PromiseState<R, E = unknown> {
30
36
  * };
31
37
  * ```
32
38
  */
33
- export interface UsePromiseStateOptions<R, E = unknown> {
39
+ export interface UsePromiseStateOptions<R, E = unknown> extends PromiseStateCallbacks<R, E> {
34
40
  /** Initial status, defaults to IDLE */
35
41
  initialStatus?: PromiseStatus;
36
- /** Callback invoked on success */
37
- onSuccess?: (result: R) => void;
38
- /** Callback invoked on error */
39
- onError?: (error: E) => void;
40
42
  }
41
43
  /**
42
44
  * Return type for usePromiseState hook
@@ -1 +1 @@
1
- {"version":3,"file":"usePromiseState.d.ts","sourceRoot":"","sources":["../../src/core/usePromiseState.ts"],"names":[],"mappings":"AAgBA;;GAEG;AACH,oBAAY,aAAa;IACvB,IAAI,SAAS;IACb,OAAO,YAAY;IACnB,OAAO,YAAY;IACnB,KAAK,UAAU;CAChB;AAED,MAAM,WAAW,YAAY,CAAC,CAAC,EAAE,CAAC,GAAG,OAAO;IAC1C,oCAAoC;IACpC,MAAM,EAAE,aAAa,CAAC;IACtB,qCAAqC;IACrC,OAAO,EAAE,OAAO,CAAC;IACjB,uBAAuB;IACvB,MAAM,EAAE,CAAC,GAAG,SAAS,CAAC;IACtB,sBAAsB;IACtB,KAAK,EAAE,CAAC,GAAG,SAAS,CAAC;CACtB;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,WAAW,sBAAsB,CAAC,CAAC,EAAE,CAAC,GAAG,OAAO;IACpD,uCAAuC;IACvC,aAAa,CAAC,EAAE,aAAa,CAAC;IAC9B,kCAAkC;IAClC,SAAS,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,KAAK,IAAI,CAAC;IAChC,gCAAgC;IAChC,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,IAAI,CAAC;CAC9B;A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AI,CAAC;IACvB,+BAA+B;IAC/B,KAAK,EAAE,MAAM,IAAI,CAAC;CACnB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,wBAAgB,YAAY,IAAI,kBAAkB,CA8BjD"}
1
+ {"version":3,"file":"useRequestId.d.ts","sourceRoot":"","sources":["../../src/core/useRequestId.ts"],"names":[],"mappings":"AAeA;;GAEG;AACH,MAAM,WAAW,kBAAkB;IACjC,wDAAwD;IACxD,QAAQ,EAAE,MAAM,MAAM,CAAC;IACvB,8DAA8D;IAC9D,OAAO,EAAE,MAAM,MAAM,CAAC;IACtB,gDAAgD;IAChD,QAAQ,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,OAAO,CAAC;IACzC,oDAAoD;IACpD,UAAU,EAAE,MAAM,IAAI,CAAC;IACvB,+BAA+B;IAC/B,KAAK,EAAE,MAAM,IAAI,CAAC;CACnB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,wBAAgB,YAAY,IAAI,kBAAkB,CA+BjD"}
@@ -1 +1 @@
1
- {"version":3,"file":"useFetcher.d.ts","sourceRoot":"","sources":["../../src/fetcher/useFetcher.ts"],"names":[],"mappings":"AAaA,OAAO,EAEL,cAAc,EACd,aAAa,EACb,YAAY,EAEZ,cAAc,EACf,MAAM,oBAAoB,CAAC;AAG5B,OAAO,EAAE,YAAY,EAAmB,sBAAsB,EAAgB,MAAM,SAAS,CAAC;AAE9F;;;GAGG;AACH,MAAM,WAAW,iBAAiB,CAAC,CAAC,EAAE,CAAC,GAAG,OAAO,CAAE,SAAQ,cAAc,EAAE,cAAc,EAAE,sBAAsB,CAAC,CAAC,EAAE,CAAC,CAAC;CACtH;AAED,MAAM,WAAW,gBAAgB,CAAC,CAAC,EAAE,CAAC,GAAG,OAAO,CAAE,SAAQ,YAAY,CAAC,CAAC,EAAE,CAAC,CAAC;IAC1E,wEAAwE;IACxE,QAAQ,CAAC,EAAE,aAAa,CAAC;IACzB,OAAO,EAAE,CAAC,OAAO,EAAE,YAAY,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CACnD;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAgB,UAAU,CAAC,CAAC,EAAE,CAAC,GAAG,OAAO,EACvC,OAAO,CAAC,EAAE,iBAAiB,CAAC,CAAC,EAAE,CAAC,CAAC,GAChC,gBAAgB,CAAC,CAAC,EAAE,CAAC,CAAC,CAgExB"}
1
+ {"version":3,"file":"useFetcher.d.ts","sourceRoot":"","sources":["../../src/fetcher/useFetcher.ts"],"names":[],"mappings":"AAaA,OAAO,EAEL,cAAc,EACd,aAAa,EACb,YAAY,EAEZ,cAAc,EACf,MAAM,oBAAoB,CAAC;AAG5B,OAAO,EACL,YAAY,EAGZ,sBAAsB,EAEvB,MAAM,SAAS,CAAC;AAEjB;;;GAGG;AACH,MAAM,WAAW,iBAAiB,CAAC,CAAC,EAAE,CAAC,GAAG,OAAO,CAC/C,SAAQ,cAAc,EACpB,cAAc,EACd,sBAAsB,CAAC,CAAC,EAAE,CAAC,CAAC;CAC/B;AAED,MAAM,WAAW,gBAAgB,CAAC,CAAC,EAAE,CAAC,GAAG,OAAO,CAAE,SAAQ,YAAY,CAAC,CAAC,EAAE,CAAC,CAAC;IAC1E,wEAAwE;IACxE,QAAQ,CAAC,EAAE,aAAa,CAAC;IACzB,OAAO,EAAE,CAAC,OAAO,EAAE,YAAY,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CACnD;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAgB,UAAU,CAAC,CAAC,EAAE,CAAC,GAAG,OAAO,EACvC,OAAO,CAAC,EAAE,iBAAiB,CAAC,CAAC,EAAE,CAAC,CAAC,GAChC,gBAAgB,CAAC,CAAC,EAAE,CAAC,CAAC,CAsExB"}
package/dist/index.es.js CHANGED
@@ -1,82 +1,89 @@
1
- import { useRef as v, useCallback as c, useEffect as R, useState as E, useMemo as h, useSyncExternalStore as x } from "react";
2
- import { fetcherRegistrar as S, getFetcher as C } from "@ahoo-wang/fetcher";
3
- function L() {
1
+ import { useRef as v, useCallback as c, useEffect as I, useState as h, useMemo as L, useSyncExternalStore as C } from "react";
2
+ import { fetcherRegistrar as w, getFetcher as F } from "@ahoo-wang/fetcher";
3
+ function R() {
4
4
  var t = v(!1), e = c(function() {
5
5
  return t.current;
6
6
  }, []);
7
- return R(function() {
7
+ return I(function() {
8
8
  return t.current = !0, function() {
9
9
  t.current = !1;
10
10
  };
11
11
  }, []), e;
12
12
  }
13
- var w = /* @__PURE__ */ ((t) => (t.IDLE = "idle", t.LOADING = "loading", t.SUCCESS = "success", t.ERROR = "error", t))(w || {});
14
- function I(t) {
15
- const [e, r] = E(
13
+ function b(t) {
14
+ const e = v(t);
15
+ return e.current = t, e;
16
+ }
17
+ var p = /* @__PURE__ */ ((t) => (t.IDLE = "idle", t.LOADING = "loading", t.SUCCESS = "success", t.ERROR = "error", t))(p || {});
18
+ function m(t) {
19
+ const [e, r] = h(
16
20
  t?.initialStatus ?? "idle"
17
21
  /* IDLE */
18
- ), [u, a] = E(void 0), [s, n] = E(void 0), o = L(), d = c(() => {
22
+ ), [u, i] = h(void 0), [s, n] = h(void 0), o = R(), d = b(t), f = c(() => {
19
23
  o() && (r(
20
24
  "loading"
21
25
  /* LOADING */
22
26
  ), n(void 0));
23
- }, [o]), l = c(
24
- (i) => {
25
- o() && (a(i), r(
27
+ }, [o]), E = c(
28
+ (a) => {
29
+ o() && (i(a), r(
26
30
  "success"
27
31
  /* SUCCESS */
28
- ), n(void 0), t?.onSuccess?.(i));
32
+ ), n(void 0), d.current?.onSuccess?.(a));
29
33
  },
30
- [o, t]
31
- ), f = c(
32
- (i) => {
33
- o() && (n(i), r(
34
+ [o, d]
35
+ ), l = c(
36
+ (a) => {
37
+ o() && (n(a), r(
34
38
  "error"
35
39
  /* ERROR */
36
- ), a(void 0), t?.onError?.(i));
40
+ ), i(void 0), d.current?.onError?.(a));
37
41
  },
38
- [o, t]
42
+ [o, d]
39
43
  ), g = c(() => {
40
44
  o() && (r(
41
45
  "idle"
42
46
  /* IDLE */
43
- ), n(void 0), a(void 0));
47
+ ), n(void 0), i(void 0));
44
48
  }, [o]);
45
- return h(() => ({
46
- status: e,
47
- loading: e === "loading",
48
- result: u,
49
- error: s,
50
- setLoading: d,
51
- setSuccess: l,
52
- setError: f,
53
- setIdle: g
54
- }), [e, u, s, d, l, f, g]);
49
+ return L(
50
+ () => ({
51
+ status: e,
52
+ loading: e === "loading",
53
+ result: u,
54
+ error: s,
55
+ setLoading: f,
56
+ setSuccess: E,
57
+ setError: l,
58
+ setIdle: g
59
+ }),
60
+ [e, u, s, f, E, l, g]
61
+ );
55
62
  }
56
- function b() {
57
- const t = v(0), e = c(() => ++t.current, []), r = c(() => t.current, []), u = c((n) => n === t.current, []), a = c(() => {
63
+ function x() {
64
+ const t = v(0), e = c(() => ++t.current, []), r = c(() => t.current, []), u = c((n) => n === t.current, []), i = c(() => {
58
65
  t.current++;
59
66
  }, []), s = c(() => {
60
67
  t.current = 0;
61
68
  }, []);
62
- return {
69
+ return L(() => ({
63
70
  generate: e,
64
71
  current: r,
65
72
  isLatest: u,
66
- invalidate: a,
73
+ invalidate: i,
67
74
  reset: s
68
- };
75
+ }), [e, r, u, i, s]);
69
76
  }
70
77
  function q(t) {
71
- const e = I(t), r = L(), u = b(), a = c(
78
+ const e = m(t), r = R(), u = x(), i = c(
72
79
  async (n) => {
73
80
  if (!r())
74
81
  throw new Error("Component is unmounted");
75
82
  const o = u.generate();
76
83
  e.setLoading();
77
84
  try {
78
- const l = await (typeof n == "function" ? n() : n);
79
- return r() && u.isLatest(o) && e.setSuccess(l), l;
85
+ const f = await (typeof n == "function" ? n() : n);
86
+ return r() && u.isLatest(o) && e.setSuccess(f), f;
80
87
  } catch (d) {
81
88
  throw r() && u.isLatest(o) && e.setError(d), d;
82
89
  }
@@ -85,67 +92,74 @@ function q(t) {
85
92
  ), s = c(() => {
86
93
  r() && e.setIdle();
87
94
  }, [e, r]);
88
- return h(
95
+ return L(
89
96
  () => ({
90
97
  loading: e.loading,
91
98
  result: e.result,
92
99
  error: e.error,
93
- execute: a,
100
+ execute: i,
94
101
  reset: s,
95
102
  status: e.status
96
103
  }),
97
- [e.loading, e.result, e.error, a, s, e.status]
104
+ [e.loading, e.result, e.error, i, s, e.status]
98
105
  );
99
106
  }
100
107
  function y(t) {
101
108
  const e = c(
102
109
  (s) => t.addListener(s),
103
110
  [t]
104
- ), r = c(() => t.get(), [t]), u = x(e, r, r), a = c(
111
+ ), r = c(() => t.get(), [t]), u = C(e, r, r), i = c(
105
112
  (s) => t.set(s),
106
113
  [t]
107
114
  );
108
- return [u, a];
115
+ return [u, i];
109
116
  }
110
117
  function A(t) {
111
- const { fetcher: e = S.default } = t || {}, r = I(t), [u, a] = E(
118
+ const { fetcher: e = w.default } = t || {}, r = m(t), [u, i] = h(
112
119
  void 0
113
- ), s = L(), n = v(), o = b(), d = C(e), l = c(
114
- async (f) => {
115
- n.current && n.current.abort(), n.current = f.abortController ?? new AbortController(), f.abortController = n.current;
120
+ ), s = R(), n = v(), o = x(), d = b(t), f = F(e), E = c(
121
+ async (l) => {
122
+ n.current && n.current.abort(), n.current = l.abortController ?? new AbortController(), l.abortController = n.current;
116
123
  const g = o.generate();
117
124
  r.setLoading();
118
125
  try {
119
- const i = await d.exchange(f, t);
120
- s() && o.isLatest(g) && a(i);
121
- const m = await i.extractResult();
122
- s() && o.isLatest(g) && r.setSuccess(m);
123
- } catch (i) {
124
- if (i instanceof Error && i.name === "AbortError") {
126
+ const a = await f.exchange(
127
+ l,
128
+ d.current
129
+ );
130
+ s() && o.isLatest(g) && i(a);
131
+ const S = await a.extractResult();
132
+ s() && o.isLatest(g) && r.setSuccess(S);
133
+ } catch (a) {
134
+ if (a instanceof Error && a.name === "AbortError") {
125
135
  s() && r.setIdle();
126
136
  return;
127
137
  }
128
- s() && o.isLatest(g) && r.setError(i);
138
+ s() && o.isLatest(g) && r.setError(a);
129
139
  } finally {
130
- n.current === f.abortController && (n.current = void 0);
140
+ n.current === l.abortController && (n.current = void 0);
131
141
  }
132
142
  },
133
- [d, s, t, r, o]
143
+ [f, s, d, r, o]
134
144
  );
135
- return R(() => () => {
145
+ return I(() => () => {
136
146
  n.current?.abort(), n.current = void 0;
137
- }, []), h(() => ({
138
- ...r,
139
- exchange: u,
140
- execute: l
141
- }), [r, u, l]);
147
+ }, []), L(
148
+ () => ({
149
+ ...r,
150
+ exchange: u,
151
+ execute: E
152
+ }),
153
+ [r, u, E]
154
+ );
142
155
  }
143
156
  export {
144
- w as PromiseStatus,
157
+ p as PromiseStatus,
145
158
  q as useExecutePromise,
146
159
  A as useFetcher,
147
160
  y as useKeyStorage,
148
- I as usePromiseState,
149
- b as useRequestId
161
+ b as useLatest,
162
+ m as usePromiseState,
163
+ x as useRequestId
150
164
  };
151
165
  //# sourceMappingURL=index.es.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.es.js","sources":["../../../node_modules/.pnpm/react-use@17.6.0_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/react-use/esm/useMountedState.js","../src/core/usePromiseState.ts","../src/core/useRequestId.ts","../src/core/useExecutePromise.ts","../src/storage/useKeyStorage.ts","../src/fetcher/useFetcher.ts"],"sourcesContent":["import { useCallback, useEffect, useRef } from 'react';\nexport default function useMountedState() {\n var mountedRef = useRef(false);\n var get = useCallback(function () { return mountedRef.current; }, []);\n useEffect(function () {\n mountedRef.current = true;\n return function () {\n mountedRef.current = false;\n };\n }, []);\n return get;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { useCallback, useMemo, useState } from 'react';\nimport { useMountedState } from 'react-use';\n\n/**\n * Enumeration of possible promise execution states\n */\nexport enum PromiseStatus {\n IDLE = 'idle',\n LOADING = 'loading',\n SUCCESS = 'success',\n ERROR = 'error',\n}\n\nexport interface PromiseState<R, E = unknown> {\n /** Current status of the promise */\n status: PromiseStatus;\n /** Indicates if currently loading */\n loading: boolean;\n /** The result value */\n result: R | undefined;\n /** The error value */\n error: E | undefined;\n}\n\n/**\n * Options for configuring usePromiseState behavior\n * @template R - The type of result\n *\n * @example\n * ```typescript\n * const options: UsePromiseStateOptions<string> = {\n * initialStatus: PromiseStatus.IDLE,\n * onSuccess: (result) => console.log('Success:', result),\n * onError: (error) => console.error('Error:', error),\n * };\n * ```\n */\nexport interface UsePromiseStateOptions<R, E = unknown> {\n /** Initial status, defaults to IDLE */\n initialStatus?: PromiseStatus;\n /** Callback invoked on success */\n onSuccess?: (result: R) => void;\n /** Callback invoked on error */\n onError?: (error: E) => void;\n}\n\n/**\n * Return type for usePromiseState hook\n * @template R - The type of result\n */\nexport interface UsePromiseStateReturn<R, E = unknown> extends PromiseState<R, E> {\n /** Set status to LOADING */\n setLoading: () => void;\n /** Set status to SUCCESS with result */\n setSuccess: (result: R) => void;\n /** Set status to ERROR with error */\n setError: (error: E) => void;\n /** Set status to IDLE */\n setIdle: () => void;\n}\n\n/**\n * A React hook for managing promise state without execution logic\n * @template R - The type of result\n * @param options - Configuration options\n * @returns State management object\n *\n * @example\n * ```typescript\n * import { usePromiseState, PromiseStatus } from '@ahoo-wang/fetcher-react';\n *\n * function MyComponent() {\n * const { status, loading, result, error, setSuccess, setError, setIdle } = usePromiseState<string>();\n *\n * const handleSuccess = () => setSuccess('Data loaded');\n * const handleError = () => setError(new Error('Failed to load'));\n *\n * return (\n * <div>\n * <button onClick={handleSuccess}>Set Success</button>\n * <button onClick={handleError}>Set Error</button>\n * <button onClick={setIdle}>Reset</button>\n * <p>Status: {status}</p>\n * {loading && <p>Loading...</p>}\n * {result && <p>Result: {result}</p>}\n * {error && <p>Error: {error.message}</p>}\n * </div>\n * );\n * }\n * ```\n */\nexport function usePromiseState<R = unknown, E = unknown>(\n options?: UsePromiseStateOptions<R, E>,\n): UsePromiseStateReturn<R, E> {\n const [status, setStatus] = useState<PromiseStatus>(\n options?.initialStatus ?? PromiseStatus.IDLE,\n );\n const [result, setResult] = useState<R | undefined>(undefined);\n const [error, setErrorState] = useState<E | undefined>(undefined);\n const isMounted = useMountedState();\n\n const setLoadingFn = useCallback(() => {\n if (isMounted()) {\n setStatus(PromiseStatus.LOADING);\n setErrorState(undefined);\n }\n }, [isMounted]);\n\n const setSuccessFn = useCallback(\n (result: R) => {\n if (isMounted()) {\n setResult(result);\n setStatus(PromiseStatus.SUCCESS);\n setErrorState(undefined);\n options?.onSuccess?.(result);\n }\n },\n [isMounted, options],\n );\n\n const setErrorFn = useCallback(\n (error: E) => {\n if (isMounted()) {\n setErrorState(error);\n setStatus(PromiseStatus.ERROR);\n setResult(undefined);\n options?.onError?.(error);\n }\n },\n [isMounted, options],\n );\n\n const setIdleFn = useCallback(() => {\n if (isMounted()) {\n setStatus(PromiseStatus.IDLE);\n setErrorState(undefined);\n setResult(undefined);\n }\n }, [isMounted]);\n return useMemo(() => ({\n status,\n loading: status === PromiseStatus.LOADING,\n result,\n error,\n setLoading: setLoadingFn,\n setSuccess: setSuccessFn,\n setError: setErrorFn,\n setIdle: setIdleFn,\n }), [status, result, error, setLoadingFn, setSuccessFn, setErrorFn, setIdleFn]);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { useRef, useCallback } from 'react';\n\n/**\n * Return type for useRequestId hook\n */\nexport interface UseRequestIdReturn {\n /** Generate a new request ID and get the current one */\n generate: () => number;\n /** Get the current request ID without generating a new one */\n current: () => number;\n /** Check if a given request ID is the latest */\n isLatest: (requestId: number) => boolean;\n /** Invalidate current request ID (mark as stale) */\n invalidate: () => void;\n /** Reset request ID counter */\n reset: () => void;\n}\n\n/**\n * A React hook for managing request IDs and race condition protection\n *\n * @example\n * ```typescript\n * // Basic usage\n * const requestId = useRequestId();\n *\n * const execute = async () => {\n * const id = requestId.generate();\n *\n * try {\n * const result = await someAsyncOperation();\n *\n * // Check if this is still the latest request\n * if (requestId.isLatest(id)) {\n * setState(result);\n * }\n * } catch (error) {\n * if (requestId.isLatest(id)) {\n * setError(error);\n * }\n * }\n * };\n *\n * // Manual cancellation\n * const handleCancel = () => {\n * requestId.invalidate(); // All ongoing requests will be ignored\n * };\n * ```\n *\n * @example\n * ```typescript\n * // With async operation wrapper\n * const { execute, cancel } = useAsyncOperation(async (data) => {\n * return await apiCall(data);\n * }, [requestId]);\n * ```\n */\nexport function useRequestId(): UseRequestIdReturn {\n const requestIdRef = useRef<number>(0);\n\n const generate = useCallback((): number => {\n return ++requestIdRef.current;\n }, []);\n\n const current = useCallback((): number => {\n return requestIdRef.current;\n }, []);\n\n const isLatest = useCallback((requestId: number): boolean => {\n return requestId === requestIdRef.current;\n }, []);\n\n const invalidate = useCallback((): void => {\n requestIdRef.current++;\n }, []);\n\n const reset = useCallback((): void => {\n requestIdRef.current = 0;\n }, []);\n\n return {\n generate,\n current,\n isLatest,\n invalidate,\n reset,\n };\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { useCallback, useMemo } from 'react';\nimport { useMountedState } from 'react-use';\nimport { usePromiseState, PromiseState, UsePromiseStateOptions } from './usePromiseState';\nimport { useRequestId } from './useRequestId';\n\n/**\n * Type definition for a function that returns a Promise\n * @template R - The type of value the promise will resolve to\n */\nexport type PromiseSupplier<R> = () => Promise<R>;\n\n/**\n * Interface defining the return type of useExecutePromise hook\n * @template R - The type of the result value\n */\nexport interface UseExecutePromiseReturn<R, E = unknown>\n extends PromiseState<R, E> {\n /** Function to execute a promise supplier or promise */\n execute: (input: PromiseSupplier<R> | Promise<R>) => Promise<R>;\n /** Function to reset the state to initial values */\n reset: () => void;\n}\n\n/**\n * A React hook for managing asynchronous operations with proper state handling\n * @template R - The type of the result value\n * @returns An object containing the current state and control functions\n *\n * @example\n * ```typescript\n * import { useExecutePromise } from '@ahoo-wang/fetcher-react';\n *\n * function MyComponent() {\n * const { loading, result, error, execute, reset } = useExecutePromise<string>();\n *\n * const fetchData = async () => {\n * const response = await fetch('/api/data');\n * return response.text();\n * };\n *\n * const handleFetch = () => {\n * execute(fetchData);\n * };\n *\n * const handleReset = () => {\n * reset();\n * };\n *\n * if (loading) return <div>Loading...</div>;\n * if (error) return <div>Error: {error.message}</div>;\n * return (\n * <div>\n * <button onClick={handleFetch}>Fetch Data</button>\n * <button onClick={handleReset}>Reset</button>\n * {result && <p>{result}</p>}\n * </div>\n * );\n * }\n * ```\n */\nexport function useExecutePromise<R = unknown, E = unknown>(options?: UsePromiseStateOptions<R, E>): UseExecutePromiseReturn<R, E> {\n const state = usePromiseState<R, E>(options);\n const isMounted = useMountedState();\n const requestId = useRequestId();\n\n /**\n * Execute a promise supplier or promise and manage its state\n * @param input - A function that returns a Promise or a Promise to be executed\n * @returns A Promise that resolves with the result of the executed promise\n */\n const execute = useCallback(\n async (input: PromiseSupplier<R> | Promise<R>): Promise<R> => {\n if (!isMounted()) {\n throw new Error('Component is unmounted');\n }\n const currentRequestId = requestId.generate();\n state.setLoading();\n try {\n const promise = typeof input === 'function' ? input() : input;\n const data = await promise;\n\n if (isMounted() && requestId.isLatest(currentRequestId)) {\n state.setSuccess(data);\n }\n return data;\n } catch (err) {\n if (isMounted() && requestId.isLatest(currentRequestId)) {\n state.setError(err as E);\n }\n throw err;\n }\n },\n [state, isMounted, requestId],\n );\n\n /**\n * Reset the state to initial values\n */\n const reset = useCallback(() => {\n if (isMounted()) {\n state.setIdle();\n }\n }, [state, isMounted]);\n\n return useMemo(\n () => ({\n loading: state.loading,\n result: state.result,\n error: state.error,\n execute,\n reset,\n status: state.status,\n }),\n [state.loading, state.result, state.error, execute, reset, state.status],\n );\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { useCallback, useSyncExternalStore } from 'react';\nimport { KeyStorage } from '@ahoo-wang/fetcher-storage';\n\n/**\n * A React hook that provides state management for a KeyStorage instance.\n * Subscribes to storage changes and returns the current value along with a setter function.\n *\n * @template T - The type of value stored in the key storage\n * @param keyStorage - The KeyStorage instance to subscribe to and manage\n * @returns A tuple containing the current stored value and a function to update it\n */\nexport function useKeyStorage<T>(\n keyStorage: KeyStorage<T>,\n): [T | null, (value: T) => void] {\n const subscribe = useCallback(\n (callback: () => void) => keyStorage.addListener(callback),\n [keyStorage],\n );\n const getSnapshot = useCallback(() => keyStorage.get(), [keyStorage]);\n const value = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n const setValue = useCallback(\n (value: T) => keyStorage.set(value),\n [keyStorage],\n );\n return [value, setValue];\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n fetcherRegistrar,\n FetcherCapable,\n FetchExchange,\n FetchRequest,\n getFetcher,\n RequestOptions,\n} from '@ahoo-wang/fetcher';\nimport { useRef, useCallback, useEffect, useState, useMemo } from 'react';\nimport { useMountedState } from 'react-use';\nimport { PromiseState, usePromiseState, UsePromiseStateOptions, useRequestId } from '../core';\n\n/**\n * Configuration options for the useFetcher hook.\n * Extends RequestOptions and FetcherCapable interfaces.\n */\nexport interface UseFetcherOptions<R, E = unknown> extends RequestOptions, FetcherCapable, UsePromiseStateOptions<R, E> {\n}\n\nexport interface UseFetcherReturn<R, E = unknown> extends PromiseState<R, E> {\n /** The FetchExchange object representing the ongoing fetch operation */\n exchange?: FetchExchange;\n execute: (request: FetchRequest) => Promise<void>;\n}\n\n/**\n * A React hook for managing asynchronous operations with proper state handling\n * @param options - Configuration options for the fetcher\n * @returns An object containing the current state and control functions\n *\n * @example\n * ```typescript\n * import { useFetcher } from '@ahoo-wang/fetcher-react';\n *\n * function MyComponent() {\n * const { loading, result, error, execute } = useFetcher<string>();\n *\n * const handleFetch = () => {\n * execute({ url: '/api/data', method: 'GET' });\n * };\n *\n * if (loading) return <div>Loading...</div>;\n * if (error) return <div>Error: {error.message}</div>;\n * return (\n * <div>\n * <button onClick={handleFetch}>Fetch Data</button>\n * {result && <p>{result}</p>}\n * </div>\n * );\n * }\n * ```\n */\nexport function useFetcher<R, E = unknown>(\n options?: UseFetcherOptions<R, E>,\n): UseFetcherReturn<R, E> {\n const { fetcher = fetcherRegistrar.default } = options || {};\n const state = usePromiseState<R, E>(options);\n const [exchange, setExchange] = useState<FetchExchange | undefined>(\n undefined,\n );\n const isMounted = useMountedState();\n const abortControllerRef = useRef<AbortController | undefined>();\n const requestId = useRequestId();\n\n const currentFetcher = getFetcher(fetcher);\n /**\n * Execute the fetch operation.\n * Cancels any ongoing fetch before starting a new one.\n */\n const execute = useCallback(\n async (request: FetchRequest) => {\n if (abortControllerRef.current) {\n abortControllerRef.current.abort();\n }\n abortControllerRef.current =\n request.abortController ?? new AbortController();\n request.abortController = abortControllerRef.current;\n const currentRequestId = requestId.generate();\n state.setLoading();\n try {\n const exchange = await currentFetcher.exchange(request, options);\n if (isMounted() && requestId.isLatest(currentRequestId)) {\n setExchange(exchange);\n }\n const result = await exchange.extractResult<R>();\n if (isMounted() && requestId.isLatest(currentRequestId)) {\n state.setSuccess(result);\n }\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') {\n if (isMounted()) {\n state.setIdle();\n }\n return;\n }\n if (isMounted() && requestId.isLatest(currentRequestId)) {\n state.setError(error as E);\n }\n } finally {\n if (abortControllerRef.current === request.abortController) {\n abortControllerRef.current = undefined;\n }\n }\n },\n [currentFetcher, isMounted, options, state, requestId],\n );\n\n useEffect(() => {\n return () => {\n abortControllerRef.current?.abort();\n abortControllerRef.current = undefined;\n };\n }, []);\n return useMemo(() => ({\n ...state,\n exchange,\n execute,\n }), [state, exchange, execute]);\n}\n"],"names":["useMountedState","mountedRef","useRef","get","useCallback","useEffect","PromiseStatus","usePromiseState","options","status","setStatus","useState","result","setResult","error","setErrorState","isMounted","setLoadingFn","setSuccessFn","setErrorFn","setIdleFn","useMemo","useRequestId","requestIdRef","generate","current","isLatest","requestId","invalidate","reset","useExecutePromise","state","execute","input","currentRequestId","data","err","useKeyStorage","keyStorage","subscribe","callback","getSnapshot","value","useSyncExternalStore","setValue","useFetcher","fetcher","fetcherRegistrar","exchange","setExchange","abortControllerRef","currentFetcher","getFetcher","request"],"mappings":";;AACe,SAASA,IAAkB;AACtC,MAAIC,IAAaC,EAAO,EAAK,GACzBC,IAAMC,EAAY,WAAY;AAAE,WAAOH,EAAW;AAAA,EAAS,GAAG,EAAE;AACpE,SAAAI,EAAU,WAAY;AAClB,WAAAJ,EAAW,UAAU,IACd,WAAY;AACf,MAAAA,EAAW,UAAU;AAAA,IACzB;AAAA,EACJ,GAAG,CAAA,CAAE,GACEE;AACX;ACQO,IAAKG,sBAAAA,OACVA,EAAA,OAAO,QACPA,EAAA,UAAU,WACVA,EAAA,UAAU,WACVA,EAAA,QAAQ,SAJEA,IAAAA,KAAA,CAAA,CAAA;AAqFL,SAASC,EACdC,GAC6B;AAC7B,QAAM,CAACC,GAAQC,CAAS,IAAIC;AAAA,IAC1BH,GAAS,iBAAiB;AAAA;AAAA,EAAA,GAEtB,CAACI,GAAQC,CAAS,IAAIF,EAAwB,MAAS,GACvD,CAACG,GAAOC,CAAa,IAAIJ,EAAwB,MAAS,GAC1DK,IAAYhB,EAAA,GAEZiB,IAAeb,EAAY,MAAM;AACrC,IAAIY,QACFN;AAAA,MAAU;AAAA;AAAA,IAAA,GACVK,EAAc,MAAS;AAAA,EAE3B,GAAG,CAACC,CAAS,CAAC,GAERE,IAAed;AAAA,IACnB,CAACQ,MAAc;AACb,MAAII,QACFH,EAAUD,CAAM,GAChBF;AAAA,QAAU;AAAA;AAAA,MAAA,GACVK,EAAc,MAAS,GACvBP,GAAS,YAAYI,CAAM;AAAA,IAE/B;AAAA,IACA,CAACI,GAAWR,CAAO;AAAA,EAAA,GAGfW,IAAaf;AAAA,IACjB,CAACU,MAAa;AACZ,MAAIE,QACFD,EAAcD,CAAK,GACnBJ;AAAA,QAAU;AAAA;AAAA,MAAA,GACV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A,IACE,CAACD,GAAOiB,GAAUhB,CAAO,CAAC;AAChC;","x_google_ignoreList":[0]}
1
+ {"version":3,"file":"index.es.js","sources":["../../../node_modules/.pnpm/react-use@17.6.0_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/react-use/esm/useMountedState.js","../src/core/useLatest.ts","../src/core/usePromiseState.ts","../src/core/useRequestId.ts","../src/core/useExecutePromise.ts","../src/storage/useKeyStorage.ts","../src/fetcher/useFetcher.ts"],"sourcesContent":["import { useCallback, useEffect, useRef } from 'react';\nexport default function useMountedState() {\n var mountedRef = useRef(false);\n var get = useCallback(function () { return mountedRef.current; }, []);\n useEffect(function () {\n mountedRef.current = true;\n return function () {\n mountedRef.current = false;\n };\n }, []);\n return get;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { useRef } from 'react';\n\n/**\n * A React hook that returns a ref containing the latest value, useful for accessing the current value in async callbacks.\n *\n * @template T - The type of the value\n * @param value - The value to track\n * @returns A ref object containing the latest value\n *\n * @example\n * ```typescript\n * import { useLatest } from '@ahoo-wang/fetcher-react';\n *\n * const MyComponent = () => {\n * const [count, setCount] = useState(0);\n * const latestCount = useLatest(count);\n *\n * const handleAsync = async () => {\n * await someAsyncOperation();\n * console.log('Latest count:', latestCount.current); // Always the latest\n * };\n *\n * return (\n * <div>\n * <p>Count: {count}</p>\n * <button onClick={() => setCount(c => c + 1)}>Increment</button>\n * <button onClick={handleAsync}>Async Log</button>\n * </div>\n * );\n * };\n * ```\n */\nexport function useLatest<T>(value: T) {\n const ref = useRef(value);\n ref.current = value;\n return ref;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { useCallback, useMemo, useState } from 'react';\nimport { useMountedState } from 'react-use';\nimport { useLatest } from './useLatest';\n\n/**\n * Enumeration of possible promise execution states\n */\nexport enum PromiseStatus {\n IDLE = 'idle',\n LOADING = 'loading',\n SUCCESS = 'success',\n ERROR = 'error',\n}\n\nexport interface PromiseState<R, E = unknown> {\n /** Current status of the promise */\n status: PromiseStatus;\n /** Indicates if currently loading */\n loading: boolean;\n /** The result value */\n result: R | undefined;\n /** The error value */\n error: E | undefined;\n}\n\nexport interface PromiseStateCallbacks<R, E = unknown> {\n /** Callback invoked on success */\n onSuccess?: (result: R) => void;\n /** Callback invoked on error */\n onError?: (error: E) => void;\n}\n\n/**\n * Options for configuring usePromiseState behavior\n * @template R - The type of result\n *\n * @example\n * ```typescript\n * const options: UsePromiseStateOptions<string> = {\n * initialStatus: PromiseStatus.IDLE,\n * onSuccess: (result) => console.log('Success:', result),\n * onError: (error) => console.error('Error:', error),\n * };\n * ```\n */\nexport interface UsePromiseStateOptions<R, E = unknown> extends PromiseStateCallbacks<R, E> {\n /** Initial status, defaults to IDLE */\n initialStatus?: PromiseStatus;\n}\n\n/**\n * Return type for usePromiseState hook\n * @template R - The type of result\n */\nexport interface UsePromiseStateReturn<R, E = unknown>\n extends PromiseState<R, E> {\n /** Set status to LOADING */\n setLoading: () => void;\n /** Set status to SUCCESS with result */\n setSuccess: (result: R) => void;\n /** Set status to ERROR with error */\n setError: (error: E) => void;\n /** Set status to IDLE */\n setIdle: () => void;\n}\n\n/**\n * A React hook for managing promise state without execution logic\n * @template R - The type of result\n * @param options - Configuration options\n * @returns State management object\n *\n * @example\n * ```typescript\n * import { usePromiseState, PromiseStatus } from '@ahoo-wang/fetcher-react';\n *\n * function MyComponent() {\n * const { status, loading, result, error, setSuccess, setError, setIdle } = usePromiseState<string>();\n *\n * const handleSuccess = () => setSuccess('Data loaded');\n * const handleError = () => setError(new Error('Failed to load'));\n *\n * return (\n * <div>\n * <button onClick={handleSuccess}>Set Success</button>\n * <button onClick={handleError}>Set Error</button>\n * <button onClick={setIdle}>Reset</button>\n * <p>Status: {status}</p>\n * {loading && <p>Loading...</p>}\n * {result && <p>Result: {result}</p>}\n * {error && <p>Error: {error.message}</p>}\n * </div>\n * );\n * }\n * ```\n */\nexport function usePromiseState<R = unknown, E = unknown>(\n options?: UsePromiseStateOptions<R, E>,\n): UsePromiseStateReturn<R, E> {\n const [status, setStatus] = useState<PromiseStatus>(\n options?.initialStatus ?? PromiseStatus.IDLE,\n );\n const [result, setResult] = useState<R | undefined>(undefined);\n const [error, setErrorState] = useState<E | undefined>(undefined);\n const isMounted = useMountedState();\n const latestOptions = useLatest(options);\n const setLoadingFn = useCallback(() => {\n if (isMounted()) {\n setStatus(PromiseStatus.LOADING);\n setErrorState(undefined);\n }\n }, [isMounted]);\n\n const setSuccessFn = useCallback(\n (result: R) => {\n if (isMounted()) {\n setResult(result);\n setStatus(PromiseStatus.SUCCESS);\n setErrorState(undefined);\n latestOptions.current?.onSuccess?.(result);\n }\n },\n [isMounted, latestOptions],\n );\n\n const setErrorFn = useCallback(\n (error: E) => {\n if (isMounted()) {\n setErrorState(error);\n setStatus(PromiseStatus.ERROR);\n setResult(undefined);\n latestOptions.current?.onError?.(error);\n }\n },\n [isMounted, latestOptions],\n );\n\n const setIdleFn = useCallback(() => {\n if (isMounted()) {\n setStatus(PromiseStatus.IDLE);\n setErrorState(undefined);\n setResult(undefined);\n }\n }, [isMounted]);\n return useMemo(\n () => ({\n status,\n loading: status === PromiseStatus.LOADING,\n result,\n error,\n setLoading: setLoadingFn,\n setSuccess: setSuccessFn,\n setError: setErrorFn,\n setIdle: setIdleFn,\n }),\n [status, result, error, setLoadingFn, setSuccessFn, setErrorFn, setIdleFn],\n );\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { useRef, useCallback, useMemo } from 'react';\n\n/**\n * Return type for useRequestId hook\n */\nexport interface UseRequestIdReturn {\n /** Generate a new request ID and get the current one */\n generate: () => number;\n /** Get the current request ID without generating a new one */\n current: () => number;\n /** Check if a given request ID is the latest */\n isLatest: (requestId: number) => boolean;\n /** Invalidate current request ID (mark as stale) */\n invalidate: () => void;\n /** Reset request ID counter */\n reset: () => void;\n}\n\n/**\n * A React hook for managing request IDs and race condition protection\n *\n * @example\n * ```typescript\n * // Basic usage\n * const requestId = useRequestId();\n *\n * const execute = async () => {\n * const id = requestId.generate();\n *\n * try {\n * const result = await someAsyncOperation();\n *\n * // Check if this is still the latest request\n * if (requestId.isLatest(id)) {\n * setState(result);\n * }\n * } catch (error) {\n * if (requestId.isLatest(id)) {\n * setError(error);\n * }\n * }\n * };\n *\n * // Manual cancellation\n * const handleCancel = () => {\n * requestId.invalidate(); // All ongoing requests will be ignored\n * };\n * ```\n *\n * @example\n * ```typescript\n * // With async operation wrapper\n * const { execute, cancel } = useAsyncOperation(async (data) => {\n * return await apiCall(data);\n * }, [requestId]);\n * ```\n */\nexport function useRequestId(): UseRequestIdReturn {\n const requestIdRef = useRef<number>(0);\n\n const generate = useCallback((): number => {\n return ++requestIdRef.current;\n }, []);\n\n const current = useCallback((): number => {\n return requestIdRef.current;\n }, []);\n\n const isLatest = useCallback((requestId: number): boolean => {\n return requestId === requestIdRef.current;\n }, []);\n\n const invalidate = useCallback((): void => {\n requestIdRef.current++;\n }, []);\n\n const reset = useCallback((): void => {\n requestIdRef.current = 0;\n }, []);\n return useMemo(() => {\n return {\n generate,\n current,\n isLatest,\n invalidate,\n reset,\n };\n }, [generate, current, isLatest, invalidate, reset]);\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { useCallback, useMemo } from 'react';\nimport { useMountedState } from 'react-use';\nimport { usePromiseState, PromiseState, UsePromiseStateOptions } from './usePromiseState';\nimport { useRequestId } from './useRequestId';\n\n/**\n * Type definition for a function that returns a Promise\n * @template R - The type of value the promise will resolve to\n */\nexport type PromiseSupplier<R> = () => Promise<R>;\n\n/**\n * Interface defining the return type of useExecutePromise hook\n * @template R - The type of the result value\n */\nexport interface UseExecutePromiseReturn<R, E = unknown>\n extends PromiseState<R, E> {\n /** Function to execute a promise supplier or promise */\n execute: (input: PromiseSupplier<R> | Promise<R>) => Promise<R>;\n /** Function to reset the state to initial values */\n reset: () => void;\n}\n\n/**\n * A React hook for managing asynchronous operations with proper state handling\n * @template R - The type of the result value\n * @returns An object containing the current state and control functions\n *\n * @example\n * ```typescript\n * import { useExecutePromise } from '@ahoo-wang/fetcher-react';\n *\n * function MyComponent() {\n * const { loading, result, error, execute, reset } = useExecutePromise<string>();\n *\n * const fetchData = async () => {\n * const response = await fetch('/api/data');\n * return response.text();\n * };\n *\n * const handleFetch = () => {\n * execute(fetchData);\n * };\n *\n * const handleReset = () => {\n * reset();\n * };\n *\n * if (loading) return <div>Loading...</div>;\n * if (error) return <div>Error: {error.message}</div>;\n * return (\n * <div>\n * <button onClick={handleFetch}>Fetch Data</button>\n * <button onClick={handleReset}>Reset</button>\n * {result && <p>{result}</p>}\n * </div>\n * );\n * }\n * ```\n */\nexport function useExecutePromise<R = unknown, E = unknown>(options?: UsePromiseStateOptions<R, E>): UseExecutePromiseReturn<R, E> {\n const state = usePromiseState<R, E>(options);\n const isMounted = useMountedState();\n const requestId = useRequestId();\n\n /**\n * Execute a promise supplier or promise and manage its state\n * @param input - A function that returns a Promise or a Promise to be executed\n * @returns A Promise that resolves with the result of the executed promise\n */\n const execute = useCallback(\n async (input: PromiseSupplier<R> | Promise<R>): Promise<R> => {\n if (!isMounted()) {\n throw new Error('Component is unmounted');\n }\n const currentRequestId = requestId.generate();\n state.setLoading();\n try {\n const promise = typeof input === 'function' ? input() : input;\n const data = await promise;\n\n if (isMounted() && requestId.isLatest(currentRequestId)) {\n state.setSuccess(data);\n }\n return data;\n } catch (err) {\n if (isMounted() && requestId.isLatest(currentRequestId)) {\n state.setError(err as E);\n }\n throw err;\n }\n },\n [state, isMounted, requestId],\n );\n\n /**\n * Reset the state to initial values\n */\n const reset = useCallback(() => {\n if (isMounted()) {\n state.setIdle();\n }\n }, [state, isMounted]);\n\n return useMemo(\n () => ({\n loading: state.loading,\n result: state.result,\n error: state.error,\n execute,\n reset,\n status: state.status,\n }),\n [state.loading, state.result, state.error, execute, reset, state.status],\n );\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { useCallback, useSyncExternalStore } from 'react';\nimport { KeyStorage } from '@ahoo-wang/fetcher-storage';\n\n/**\n * A React hook that provides state management for a KeyStorage instance.\n * Subscribes to storage changes and returns the current value along with a setter function.\n *\n * @template T - The type of value stored in the key storage\n * @param keyStorage - The KeyStorage instance to subscribe to and manage\n * @returns A tuple containing the current stored value and a function to update it\n */\nexport function useKeyStorage<T>(\n keyStorage: KeyStorage<T>,\n): [T | null, (value: T) => void] {\n const subscribe = useCallback(\n (callback: () => void) => keyStorage.addListener(callback),\n [keyStorage],\n );\n const getSnapshot = useCallback(() => keyStorage.get(), [keyStorage]);\n const value = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n const setValue = useCallback(\n (value: T) => keyStorage.set(value),\n [keyStorage],\n );\n return [value, setValue];\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n fetcherRegistrar,\n FetcherCapable,\n FetchExchange,\n FetchRequest,\n getFetcher,\n RequestOptions,\n} from '@ahoo-wang/fetcher';\nimport { useRef, useCallback, useEffect, useState, useMemo } from 'react';\nimport { useMountedState } from 'react-use';\nimport {\n PromiseState,\n useLatest,\n usePromiseState,\n UsePromiseStateOptions,\n useRequestId,\n} from '../core';\n\n/**\n * Configuration options for the useFetcher hook.\n * Extends RequestOptions and FetcherCapable interfaces.\n */\nexport interface UseFetcherOptions<R, E = unknown>\n extends RequestOptions,\n FetcherCapable,\n UsePromiseStateOptions<R, E> {\n}\n\nexport interface UseFetcherReturn<R, E = unknown> extends PromiseState<R, E> {\n /** The FetchExchange object representing the ongoing fetch operation */\n exchange?: FetchExchange;\n execute: (request: FetchRequest) => Promise<void>;\n}\n\n/**\n * A React hook for managing asynchronous operations with proper state handling\n * @param options - Configuration options for the fetcher\n * @returns An object containing the current state and control functions\n *\n * @example\n * ```typescript\n * import { useFetcher } from '@ahoo-wang/fetcher-react';\n *\n * function MyComponent() {\n * const { loading, result, error, execute } = useFetcher<string>();\n *\n * const handleFetch = () => {\n * execute({ url: '/api/data', method: 'GET' });\n * };\n *\n * if (loading) return <div>Loading...</div>;\n * if (error) return <div>Error: {error.message}</div>;\n * return (\n * <div>\n * <button onClick={handleFetch}>Fetch Data</button>\n * {result && <p>{result}</p>}\n * </div>\n * );\n * }\n * ```\n */\nexport function useFetcher<R, E = unknown>(\n options?: UseFetcherOptions<R, E>,\n): UseFetcherReturn<R, E> {\n const { fetcher = fetcherRegistrar.default } = options || {};\n const state = usePromiseState<R, E>(options);\n const [exchange, setExchange] = useState<FetchExchange | undefined>(\n undefined,\n );\n const isMounted = useMountedState();\n const abortControllerRef = useRef<AbortController | undefined>();\n const requestId = useRequestId();\n const latestOptions = useLatest(options);\n const currentFetcher = getFetcher(fetcher);\n /**\n * Execute the fetch operation.\n * Cancels any ongoing fetch before starting a new one.\n */\n const execute = useCallback(\n async (request: FetchRequest) => {\n if (abortControllerRef.current) {\n abortControllerRef.current.abort();\n }\n abortControllerRef.current =\n request.abortController ?? new AbortController();\n request.abortController = abortControllerRef.current;\n const currentRequestId = requestId.generate();\n state.setLoading();\n try {\n const exchange = await currentFetcher.exchange(\n request,\n latestOptions.current,\n );\n if (isMounted() && requestId.isLatest(currentRequestId)) {\n setExchange(exchange);\n }\n const result = await exchange.extractResult<R>();\n if (isMounted() && requestId.isLatest(currentRequestId)) {\n state.setSuccess(result);\n }\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') {\n if (isMounted()) {\n state.setIdle();\n }\n return;\n }\n if (isMounted() && requestId.isLatest(currentRequestId)) {\n state.setError(error as E);\n }\n } finally {\n if (abortControllerRef.current === request.abortController) {\n abortControllerRef.current = undefined;\n }\n }\n },\n [currentFetcher, isMounted, latestOptions, state, requestId],\n );\n\n useEffect(() => {\n return () => {\n abortControllerRef.current?.abort();\n abortControllerRef.current = undefined;\n };\n }, []);\n return useMemo(\n () => ({\n ...state,\n exchange,\n execute,\n }),\n [state, exchange, execute],\n );\n}\n"],"names":["useMountedState","mountedRef","useRef","get","useCallback","useEffect","useLatest","value","ref","PromiseStatus","usePromiseState","options","status","setStatus","useState","result","setResult","error","setErrorState","isMounted","latestOptions","setLoadingFn","setSuccessFn","setErrorFn","setIdleFn","useMemo","useRequestId","requestIdRef","generate","current","isLatest","requestId","invalidate","reset","useExecutePromise","state","execute","input","currentRequestId","data","err","useKeyStorage","keyStorage","subscribe","callback","getSnapshot","useSyncExternalStore","setValue","useFetcher","fetcher","fetcherRegistrar","exchange","setExchange","abortControllerRef","currentFetcher","getFetcher","request"],"mappings":";;AACe,SAASA,IAAkB;AACtC,MAAIC,IAAaC,EAAO,EAAK,GACzBC,IAAMC,EAAY,WAAY;AAAE,WAAOH,EAAW;AAAA,EAAS,GAAG,EAAE;AACpE,SAAAI,EAAU,WAAY;AAClB,WAAAJ,EAAW,UAAU,IACd,WAAY;AACf,MAAAA,EAAW,UAAU;AAAA,IACzB;AAAA,EACJ,GAAG,CAAA,CAAE,GACEE;AACX;ACkCO,SAASG,EAAaC,GAAU;AACrC,QAAMC,IAAMN,EAAOK,CAAK;AACxB,SAAAC,EAAI,UAAUD,GACPC;AACT;AC7BO,IAAKC,sBAAAA,OACVA,EAAA,OAAO,QACPA,EAAA,UAAU,WACVA,EAAA,UAAU,WACVA,EAAA,QAAQ,SAJEA,IAAAA,KAAA,CAAA,CAAA;AAyFL,SAASC,EACdC,GAC6B;AAC7B,QAAM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F,cAAMgB,IAAW,MAAMG,EAAe;AAAA,UACpCE;AAAA,UACApC,EAAc;AAAA,QAAA;AAEhB,QAAID,EAAA,KAAeY,EAAU,SAASO,CAAgB,KACpDc,EAAYD,CAAQ;AAEtB,cAAMpC,IAAS,MAAMoC,EAAS,cAAA;AAC9B,QAAIhC,EAAA,KAAeY,EAAU,SAASO,CAAgB,KACpDH,EAAM,WAAWpB,CAAM;AAAA,MAE3B,SAASE,GAAO;AACd,YAAIA,aAAiB,SAASA,EAAM,SAAS,cAAc;AACzD,UAAIE,OACFgB,EAAM,QAAA;AAER;AAAA,QACF;AACA,QAAIhB,EAAA,KAAeY,EAAU,SAASO,CAAgB,KACpDH,EAAM,SAASlB,CAAU;AAAA,MAE7B,UAAA;AACE,QAAIoC,EAAmB,YAAYG,EAAQ,oBACzCH,EAAmB,UAAU;AAAA,MAEjC;AAAA,IACF;AAAA,IACA,CAACC,GAAgBnC,GAAWC,GAAee,GAAOJ,CAAS;AAAA,EAAA;AAG7D,SAAA1B,EAAU,MACD,MAAM;AACX,IAAAgD,EAAmB,SAAS,MAAA,GAC5BA,EAAmB,UAAU;AAAA,EAC/B,GACC,CAAA,CAAE,GACE5B;AAAA,IACL,OAAO;AAAA,MACL,GAAGU;AAAA,MACH,UAAAgB;AAAA,MACA,SAAAf;AAAA,IAAA;AAAA,IAEF,CAACD,GAAOgB,GAAUf,CAAO;AAAA,EAAA;AAE7B;","x_google_ignoreList":[0]}
package/dist/index.umd.js CHANGED
@@ -1,2 +1,2 @@
1
- (function(a,t){typeof exports=="object"&&typeof module<"u"?t(exports,require("react"),require("@ahoo-wang/fetcher")):typeof define=="function"&&define.amd?define(["exports","react","@ahoo-wang/fetcher"],t):(a=typeof globalThis<"u"?globalThis:a||self,t(a.FetcherReact={},a.React,a.Fetcher))})(this,(function(a,t,S){"use strict";function C(){var e=t.useRef(!1),r=t.useCallback(function(){return e.current},[]);return t.useEffect(function(){return e.current=!0,function(){e.current=!1}},[]),r}var v=(e=>(e.IDLE="idle",e.LOADING="loading",e.SUCCESS="success",e.ERROR="error",e))(v||{});function g(e){const[r,s]=t.useState(e?.initialStatus??"idle"),[c,i]=t.useState(void 0),[u,n]=t.useState(void 0),o=C(),d=t.useCallback(()=>{o()&&(s("loading"),n(void 0))},[o]),f=t.useCallback(l=>{o()&&(i(l),s("success"),n(void 0),e?.onSuccess?.(l))},[o,e]),b=t.useCallback(l=>{o()&&(n(l),s("error"),i(void 0),e?.onError?.(l))},[o,e]),h=t.useCallback(()=>{o()&&(s("idle"),n(void 0),i(void 0))},[o]);return t.useMemo(()=>({status:r,loading:r==="loading",result:c,error:u,setLoading:d,setSuccess:f,setError:b,setIdle:h}),[r,c,u,d,f,b,h])}function E(){const e=t.useRef(0),r=t.useCallback(()=>++e.current,[]),s=t.useCallback(()=>e.current,[]),c=t.useCallback(n=>n===e.current,[]),i=t.useCallback(()=>{e.current++},[]),u=t.useCallback(()=>{e.current=0},[]);return{generate:r,current:s,isLatest:c,invalidate:i,reset:u}}function m(e){const r=g(e),s=C(),c=E(),i=t.useCallback(async n=>{if(!s())throw new Error("Component is unmounted");const o=c.generate();r.setLoading();try{const f=await(typeof n=="function"?n():n);return s()&&c.isLatest(o)&&r.setSuccess(f),f}catch(d){throw s()&&c.isLatest(o)&&r.setError(d),d}},[r,s,c]),u=t.useCallback(()=>{s()&&r.setIdle()},[r,s]);return t.useMemo(()=>({loading:r.loading,result:r.result,error:r.error,execute:i,reset:u,status:r.status}),[r.loading,r.result,r.error,i,u,r.status])}function I(e){const r=t.useCallback(u=>e.addListener(u),[e]),s=t.useCallback(()=>e.get(),[e]),c=t.useSyncExternalStore(r,s,s),i=t.useCallback(u=>e.set(u),[e]);return[c,i]}function L(e){const{fetcher:r=S.fetcherRegistrar.default}=e||{},s=g(e),[c,i]=t.useState(void 0),u=C(),n=t.useRef(),o=E(),d=S.getFetcher(r),f=t.useCallback(async b=>{n.current&&n.current.abort(),n.current=b.abortController??new AbortController,b.abortController=n.current;const h=o.generate();s.setLoading();try{const l=await d.exchange(b,e);u()&&o.isLatest(h)&&i(l);const k=await l.extractResult();u()&&o.isLatest(h)&&s.setSuccess(k)}catch(l){if(l instanceof Error&&l.name==="AbortError"){u()&&s.setIdle();return}u()&&o.isLatest(h)&&s.setError(l)}finally{n.current===b.abortController&&(n.current=void 0)}},[d,u,e,s,o]);return t.useEffect(()=>()=>{n.current?.abort(),n.current=void 0},[]),t.useMemo(()=>({...s,exchange:c,execute:f}),[s,c,f])}a.PromiseStatus=v,a.useExecutePromise=m,a.useFetcher=L,a.useKeyStorage=I,a.usePromiseState=g,a.useRequestId=E,Object.defineProperty(a,Symbol.toStringTag,{value:"Module"})}));
1
+ (function(i,e){typeof exports=="object"&&typeof module<"u"?e(exports,require("react"),require("@ahoo-wang/fetcher")):typeof define=="function"&&define.amd?define(["exports","react","@ahoo-wang/fetcher"],e):(i=typeof globalThis<"u"?globalThis:i||self,e(i.FetcherReact={},i.React,i.Fetcher))})(this,(function(i,e,v){"use strict";function g(){var t=e.useRef(!1),r=e.useCallback(function(){return t.current},[]);return e.useEffect(function(){return t.current=!0,function(){t.current=!1}},[]),r}function E(t){const r=e.useRef(t);return r.current=t,r}var L=(t=>(t.IDLE="idle",t.LOADING="loading",t.SUCCESS="success",t.ERROR="error",t))(L||{});function S(t){const[r,s]=e.useState(t?.initialStatus??"idle"),[c,a]=e.useState(void 0),[u,n]=e.useState(void 0),o=g(),f=E(t),d=e.useCallback(()=>{o()&&(s("loading"),n(void 0))},[o]),C=e.useCallback(l=>{o()&&(a(l),s("success"),n(void 0),f.current?.onSuccess?.(l))},[o,f]),b=e.useCallback(l=>{o()&&(n(l),s("error"),a(void 0),f.current?.onError?.(l))},[o,f]),h=e.useCallback(()=>{o()&&(s("idle"),n(void 0),a(void 0))},[o]);return e.useMemo(()=>({status:r,loading:r==="loading",result:c,error:u,setLoading:d,setSuccess:C,setError:b,setIdle:h}),[r,c,u,d,C,b,h])}function m(){const t=e.useRef(0),r=e.useCallback(()=>++t.current,[]),s=e.useCallback(()=>t.current,[]),c=e.useCallback(n=>n===t.current,[]),a=e.useCallback(()=>{t.current++},[]),u=e.useCallback(()=>{t.current=0},[]);return e.useMemo(()=>({generate:r,current:s,isLatest:c,invalidate:a,reset:u}),[r,s,c,a,u])}function I(t){const r=S(t),s=g(),c=m(),a=e.useCallback(async n=>{if(!s())throw new Error("Component is unmounted");const o=c.generate();r.setLoading();try{const d=await(typeof n=="function"?n():n);return s()&&c.isLatest(o)&&r.setSuccess(d),d}catch(f){throw s()&&c.isLatest(o)&&r.setError(f),f}},[r,s,c]),u=e.useCallback(()=>{s()&&r.setIdle()},[r,s]);return e.useMemo(()=>({loading:r.loading,result:r.result,error:r.error,execute:a,reset:u,status:r.status}),[r.loading,r.result,r.error,a,u,r.status])}function k(t){const r=e.useCallback(u=>t.addListener(u),[t]),s=e.useCallback(()=>t.get(),[t]),c=e.useSyncExternalStore(r,s,s),a=e.useCallback(u=>t.set(u),[t]);return[c,a]}function F(t){const{fetcher:r=v.fetcherRegistrar.default}=t||{},s=S(t),[c,a]=e.useState(void 0),u=g(),n=e.useRef(),o=m(),f=E(t),d=v.getFetcher(r),C=e.useCallback(async b=>{n.current&&n.current.abort(),n.current=b.abortController??new AbortController,b.abortController=n.current;const h=o.generate();s.setLoading();try{const l=await d.exchange(b,f.current);u()&&o.isLatest(h)&&a(l);const w=await l.extractResult();u()&&o.isLatest(h)&&s.setSuccess(w)}catch(l){if(l instanceof Error&&l.name==="AbortError"){u()&&s.setIdle();return}u()&&o.isLatest(h)&&s.setError(l)}finally{n.current===b.abortController&&(n.current=void 0)}},[d,u,f,s,o]);return e.useEffect(()=>()=>{n.current?.abort(),n.current=void 0},[]),e.useMemo(()=>({...s,exchange:c,execute:C}),[s,c,C])}i.PromiseStatus=L,i.useExecutePromise=I,i.useFetcher=F,i.useKeyStorage=k,i.useLatest=E,i.usePromiseState=S,i.useRequestId=m,Object.defineProperty(i,Symbol.toStringTag,{value:"Module"})}));
2
2
  //# sourceMappingURL=index.umd.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.umd.js","sources":["../../../node_modules/.pnpm/react-use@17.6.0_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/react-use/esm/useMountedState.js","../src/core/usePromiseState.ts","../src/core/useRequestId.ts","../src/core/useExecutePromise.ts","../src/storage/useKeyStorage.ts","../src/fetcher/useFetcher.ts"],"sourcesContent":["import { useCallback, useEffect, useRef } from 'react';\nexport default function useMountedState() {\n var mountedRef = useRef(false);\n var get = useCallback(function () { return mountedRef.current; }, []);\n useEffect(function () {\n mountedRef.current = true;\n return function () {\n mountedRef.current = false;\n };\n }, []);\n return get;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { useCallback, useMemo, useState } from 'react';\nimport { useMountedState } from 'react-use';\n\n/**\n * Enumeration of possible promise execution states\n */\nexport enum PromiseStatus {\n IDLE = 'idle',\n LOADING = 'loading',\n SUCCESS = 'success',\n ERROR = 'error',\n}\n\nexport interface PromiseState<R, E = unknown> {\n /** Current status of the promise */\n status: PromiseStatus;\n /** Indicates if currently loading */\n loading: boolean;\n /** The result value */\n result: R | undefined;\n /** The error value */\n error: E | undefined;\n}\n\n/**\n * Options for configuring usePromiseState behavior\n * @template R - The type of result\n *\n * @example\n * ```typescript\n * const options: UsePromiseStateOptions<string> = {\n * initialStatus: PromiseStatus.IDLE,\n * onSuccess: (result) => console.log('Success:', result),\n * onError: (error) => console.error('Error:', error),\n * };\n * ```\n */\nexport interface UsePromiseStateOptions<R, E = unknown> {\n /** Initial status, defaults to IDLE */\n initialStatus?: PromiseStatus;\n /** Callback invoked on success */\n onSuccess?: (result: R) => void;\n /** Callback invoked on error */\n onError?: (error: E) => void;\n}\n\n/**\n * Return type for usePromiseState hook\n * @template R - The type of result\n */\nexport interface UsePromiseStateReturn<R, E = unknown> extends PromiseState<R, E> {\n /** Set status to LOADING */\n setLoading: () => void;\n /** Set status to SUCCESS with result */\n setSuccess: (result: R) => void;\n /** Set status to ERROR with error */\n setError: (error: E) => void;\n /** Set status to IDLE */\n setIdle: () => void;\n}\n\n/**\n * A React hook for managing promise state without execution logic\n * @template R - The type of result\n * @param options - Configuration options\n * @returns State management object\n *\n * @example\n * ```typescript\n * import { usePromiseState, PromiseStatus } from '@ahoo-wang/fetcher-react';\n *\n * function MyComponent() {\n * const { status, loading, result, error, setSuccess, setError, setIdle } = usePromiseState<string>();\n *\n * const handleSuccess = () => setSuccess('Data loaded');\n * const handleError = () => setError(new Error('Failed to load'));\n *\n * return (\n * <div>\n * <button onClick={handleSuccess}>Set Success</button>\n * <button onClick={handleError}>Set Error</button>\n * <button onClick={setIdle}>Reset</button>\n * <p>Status: {status}</p>\n * {loading && <p>Loading...</p>}\n * {result && <p>Result: {result}</p>}\n * {error && <p>Error: {error.message}</p>}\n * </div>\n * );\n * }\n * ```\n */\nexport function usePromiseState<R = unknown, E = unknown>(\n options?: UsePromiseStateOptions<R, E>,\n): UsePromiseStateReturn<R, E> {\n const [status, setStatus] = useState<PromiseStatus>(\n options?.initialStatus ?? PromiseStatus.IDLE,\n );\n const [result, setResult] = useState<R | undefined>(undefined);\n const [error, setErrorState] = useState<E | undefined>(undefined);\n const isMounted = useMountedState();\n\n const setLoadingFn = useCallback(() => {\n if (isMounted()) {\n setStatus(PromiseStatus.LOADING);\n setErrorState(undefined);\n }\n }, [isMounted]);\n\n const setSuccessFn = useCallback(\n (result: R) => {\n if (isMounted()) {\n setResult(result);\n setStatus(PromiseStatus.SUCCESS);\n setErrorState(undefined);\n options?.onSuccess?.(result);\n }\n },\n [isMounted, options],\n );\n\n const setErrorFn = useCallback(\n (error: E) => {\n if (isMounted()) {\n setErrorState(error);\n setStatus(PromiseStatus.ERROR);\n setResult(undefined);\n options?.onError?.(error);\n }\n },\n [isMounted, options],\n );\n\n const setIdleFn = useCallback(() => {\n if (isMounted()) {\n setStatus(PromiseStatus.IDLE);\n setErrorState(undefined);\n setResult(undefined);\n }\n }, [isMounted]);\n return useMemo(() => ({\n status,\n loading: status === PromiseStatus.LOADING,\n result,\n error,\n setLoading: setLoadingFn,\n setSuccess: setSuccessFn,\n setError: setErrorFn,\n setIdle: setIdleFn,\n }), [status, result, error, setLoadingFn, setSuccessFn, setErrorFn, setIdleFn]);\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { useRef, useCallback } from 'react';\n\n/**\n * Return type for useRequestId hook\n */\nexport interface UseRequestIdReturn {\n /** Generate a new request ID and get the current one */\n generate: () => number;\n /** Get the current request ID without generating a new one */\n current: () => number;\n /** Check if a given request ID is the latest */\n isLatest: (requestId: number) => boolean;\n /** Invalidate current request ID (mark as stale) */\n invalidate: () => void;\n /** Reset request ID counter */\n reset: () => void;\n}\n\n/**\n * A React hook for managing request IDs and race condition protection\n *\n * @example\n * ```typescript\n * // Basic usage\n * const requestId = useRequestId();\n *\n * const execute = async () => {\n * const id = requestId.generate();\n *\n * try {\n * const result = await someAsyncOperation();\n *\n * // Check if this is still the latest request\n * if (requestId.isLatest(id)) {\n * setState(result);\n * }\n * } catch (error) {\n * if (requestId.isLatest(id)) {\n * setError(error);\n * }\n * }\n * };\n *\n * // Manual cancellation\n * const handleCancel = () => {\n * requestId.invalidate(); // All ongoing requests will be ignored\n * };\n * ```\n *\n * @example\n * ```typescript\n * // With async operation wrapper\n * const { execute, cancel } = useAsyncOperation(async (data) => {\n * return await apiCall(data);\n * }, [requestId]);\n * ```\n */\nexport function useRequestId(): UseRequestIdReturn {\n const requestIdRef = useRef<number>(0);\n\n const generate = useCallback((): number => {\n return ++requestIdRef.current;\n }, []);\n\n const current = useCallback((): number => {\n return requestIdRef.current;\n }, []);\n\n const isLatest = useCallback((requestId: number): boolean => {\n return requestId === requestIdRef.current;\n }, []);\n\n const invalidate = useCallback((): void => {\n requestIdRef.current++;\n }, []);\n\n const reset = useCallback((): void => {\n requestIdRef.current = 0;\n }, []);\n\n return {\n generate,\n current,\n isLatest,\n invalidate,\n reset,\n };\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { useCallback, useMemo } from 'react';\nimport { useMountedState } from 'react-use';\nimport { usePromiseState, PromiseState, UsePromiseStateOptions } from './usePromiseState';\nimport { useRequestId } from './useRequestId';\n\n/**\n * Type definition for a function that returns a Promise\n * @template R - The type of value the promise will resolve to\n */\nexport type PromiseSupplier<R> = () => Promise<R>;\n\n/**\n * Interface defining the return type of useExecutePromise hook\n * @template R - The type of the result value\n */\nexport interface UseExecutePromiseReturn<R, E = unknown>\n extends PromiseState<R, E> {\n /** Function to execute a promise supplier or promise */\n execute: (input: PromiseSupplier<R> | Promise<R>) => Promise<R>;\n /** Function to reset the state to initial values */\n reset: () => void;\n}\n\n/**\n * A React hook for managing asynchronous operations with proper state handling\n * @template R - The type of the result value\n * @returns An object containing the current state and control functions\n *\n * @example\n * ```typescript\n * import { useExecutePromise } from '@ahoo-wang/fetcher-react';\n *\n * function MyComponent() {\n * const { loading, result, error, execute, reset } = useExecutePromise<string>();\n *\n * const fetchData = async () => {\n * const response = await fetch('/api/data');\n * return response.text();\n * };\n *\n * const handleFetch = () => {\n * execute(fetchData);\n * };\n *\n * const handleReset = () => {\n * reset();\n * };\n *\n * if (loading) return <div>Loading...</div>;\n * if (error) return <div>Error: {error.message}</div>;\n * return (\n * <div>\n * <button onClick={handleFetch}>Fetch Data</button>\n * <button onClick={handleReset}>Reset</button>\n * {result && <p>{result}</p>}\n * </div>\n * );\n * }\n * ```\n */\nexport function useExecutePromise<R = unknown, E = unknown>(options?: UsePromiseStateOptions<R, E>): UseExecutePromiseReturn<R, E> {\n const state = usePromiseState<R, E>(options);\n const isMounted = useMountedState();\n const requestId = useRequestId();\n\n /**\n * Execute a promise supplier or promise and manage its state\n * @param input - A function that returns a Promise or a Promise to be executed\n * @returns A Promise that resolves with the result of the executed promise\n */\n const execute = useCallback(\n async (input: PromiseSupplier<R> | Promise<R>): Promise<R> => {\n if (!isMounted()) {\n throw new Error('Component is unmounted');\n }\n const currentRequestId = requestId.generate();\n state.setLoading();\n try {\n const promise = typeof input === 'function' ? input() : input;\n const data = await promise;\n\n if (isMounted() && requestId.isLatest(currentRequestId)) {\n state.setSuccess(data);\n }\n return data;\n } catch (err) {\n if (isMounted() && requestId.isLatest(currentRequestId)) {\n state.setError(err as E);\n }\n throw err;\n }\n },\n [state, isMounted, requestId],\n );\n\n /**\n * Reset the state to initial values\n */\n const reset = useCallback(() => {\n if (isMounted()) {\n state.setIdle();\n }\n }, [state, isMounted]);\n\n return useMemo(\n () => ({\n loading: state.loading,\n result: state.result,\n error: state.error,\n execute,\n reset,\n status: state.status,\n }),\n [state.loading, state.result, state.error, execute, reset, state.status],\n );\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { useCallback, useSyncExternalStore } from 'react';\nimport { KeyStorage } from '@ahoo-wang/fetcher-storage';\n\n/**\n * A React hook that provides state management for a KeyStorage instance.\n * Subscribes to storage changes and returns the current value along with a setter function.\n *\n * @template T - The type of value stored in the key storage\n * @param keyStorage - The KeyStorage instance to subscribe to and manage\n * @returns A tuple containing the current stored value and a function to update it\n */\nexport function useKeyStorage<T>(\n keyStorage: KeyStorage<T>,\n): [T | null, (value: T) => void] {\n const subscribe = useCallback(\n (callback: () => void) => keyStorage.addListener(callback),\n [keyStorage],\n );\n const getSnapshot = useCallback(() => keyStorage.get(), [keyStorage]);\n const value = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n const setValue = useCallback(\n (value: T) => keyStorage.set(value),\n [keyStorage],\n );\n return [value, setValue];\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n fetcherRegistrar,\n FetcherCapable,\n FetchExchange,\n FetchRequest,\n getFetcher,\n RequestOptions,\n} from '@ahoo-wang/fetcher';\nimport { useRef, useCallback, useEffect, useState, useMemo } from 'react';\nimport { useMountedState } from 'react-use';\nimport { PromiseState, usePromiseState, UsePromiseStateOptions, useRequestId } from '../core';\n\n/**\n * Configuration options for the useFetcher hook.\n * Extends RequestOptions and FetcherCapable interfaces.\n */\nexport interface UseFetcherOptions<R, E = unknown> extends RequestOptions, FetcherCapable, UsePromiseStateOptions<R, E> {\n}\n\nexport interface UseFetcherReturn<R, E = unknown> extends PromiseState<R, E> {\n /** The FetchExchange object representing the ongoing fetch operation */\n exchange?: FetchExchange;\n execute: (request: FetchRequest) => Promise<void>;\n}\n\n/**\n * A React hook for managing asynchronous operations with proper state handling\n * @param options - Configuration options for the fetcher\n * @returns An object containing the current state and control functions\n *\n * @example\n * ```typescript\n * import { useFetcher } from '@ahoo-wang/fetcher-react';\n *\n * function MyComponent() {\n * const { loading, result, error, execute } = useFetcher<string>();\n *\n * const handleFetch = () => {\n * execute({ url: '/api/data', method: 'GET' });\n * };\n *\n * if (loading) return <div>Loading...</div>;\n * if (error) return <div>Error: {error.message}</div>;\n * return (\n * <div>\n * <button onClick={handleFetch}>Fetch Data</button>\n * {result && <p>{result}</p>}\n * </div>\n * );\n * }\n * ```\n */\nexport function useFetcher<R, E = unknown>(\n options?: UseFetcherOptions<R, E>,\n): UseFetcherReturn<R, E> {\n const { fetcher = fetcherRegistrar.default } = options || {};\n const state = usePromiseState<R, E>(options);\n const [exchange, setExchange] = useState<FetchExchange | undefined>(\n undefined,\n );\n const isMounted = useMountedState();\n const abortControllerRef = useRef<AbortController | undefined>();\n const requestId = useRequestId();\n\n const currentFetcher = getFetcher(fetcher);\n /**\n * Execute the fetch operation.\n * Cancels any ongoing fetch before starting a new one.\n */\n const execute = useCallback(\n async (request: FetchRequest) => {\n if (abortControllerRef.current) {\n abortControllerRef.current.abort();\n }\n abortControllerRef.current =\n request.abortController ?? new AbortController();\n request.abortController = abortControllerRef.current;\n const currentRequestId = requestId.generate();\n state.setLoading();\n try {\n const exchange = await currentFetcher.exchange(request, options);\n if (isMounted() && requestId.isLatest(currentRequestId)) {\n setExchange(exchange);\n }\n const result = await exchange.extractResult<R>();\n if (isMounted() && requestId.isLatest(currentRequestId)) {\n state.setSuccess(result);\n }\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') {\n if (isMounted()) {\n state.setIdle();\n }\n return;\n }\n if (isMounted() && requestId.isLatest(currentRequestId)) {\n state.setError(error as E);\n }\n } finally {\n if (abortControllerRef.current === request.abortController) {\n abortControllerRef.current = undefined;\n }\n }\n },\n [currentFetcher, isMounted, options, state, requestId],\n );\n\n useEffect(() => {\n return () => {\n abortControllerRef.current?.abort();\n abortControllerRef.current = undefined;\n };\n }, []);\n return useMemo(() => ({\n ...state,\n exchange,\n execute,\n }), [state, exchange, execute]);\n}\n"],"names":["useMountedState","mountedRef","useRef","get","useCallback","useEffect","PromiseStatus","usePromiseState","options","status","setStatus","useState","result","setResult","error","setErrorState","isMounted","setLoadingFn","setSuccessFn","setErrorFn","setIdleFn","useMemo","useRequestId","requestIdRef","generate","current","isLatest","requestId","invalidate","reset","useExecutePromise","state","execute","input","currentRequestId","data","err","useKeyStorage","keyStorage","subscribe","callback","getSnapshot","value","useSyncExternalStore","setValue","useFetcher","fetcher","fetcherRegistrar","exchange","setExchange","abortControllerRef","currentFetcher","getFetcher","request"],"mappings":"uUACe,SAASA,GAAkB,CACtC,IAAIC,EAAaC,EAAAA,OAAO,EAAK,EACzBC,EAAMC,EAAAA,YAAY,UAAY,CAAE,OAAOH,EAAW,OAAS,EAAG,EAAE,EACpEI,OAAAA,EAAAA,UAAU,UAAY,CAClB,OAAAJ,EAAW,QAAU,GACd,UAAY,CACfA,EAAW,QAAU,EACzB,CACJ,EAAG,CAAA,CAAE,EACEE,CACX,CCQO,IAAKG,GAAAA,IACVA,EAAA,KAAO,OACPA,EAAA,QAAU,UACVA,EAAA,QAAU,UACVA,EAAA,MAAQ,QAJEA,IAAAA,GAAA,CAAA,CAAA,EAqFL,SAASC,EACdC,EAC6B,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F,EACA,CAACC,EAAgBnC,EAAWR,EAASuB,EAAOJ,CAAS,CAAA,EAGvDtB,OAAAA,EAAAA,UAAU,IACD,IAAM,CACX6C,EAAmB,SAAS,MAAA,EAC5BA,EAAmB,QAAU,MAC/B,EACC,CAAA,CAAE,EACE7B,EAAAA,QAAQ,KAAO,CACpB,GAAGU,EACH,SAAAiB,EACA,QAAAhB,CAAA,GACE,CAACD,EAAOiB,EAAUhB,CAAO,CAAC,CAChC","x_google_ignoreList":[0]}
1
+ {"version":3,"file":"index.umd.js","sources":["../../../node_modules/.pnpm/react-use@17.6.0_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/react-use/esm/useMountedState.js","../src/core/useLatest.ts","../src/core/usePromiseState.ts","../src/core/useRequestId.ts","../src/core/useExecutePromise.ts","../src/storage/useKeyStorage.ts","../src/fetcher/useFetcher.ts"],"sourcesContent":["import { useCallback, useEffect, useRef } from 'react';\nexport default function useMountedState() {\n var mountedRef = useRef(false);\n var get = useCallback(function () { return mountedRef.current; }, []);\n useEffect(function () {\n mountedRef.current = true;\n return function () {\n mountedRef.current = false;\n };\n }, []);\n return get;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { useRef } from 'react';\n\n/**\n * A React hook that returns a ref containing the latest value, useful for accessing the current value in async callbacks.\n *\n * @template T - The type of the value\n * @param value - The value to track\n * @returns A ref object containing the latest value\n *\n * @example\n * ```typescript\n * import { useLatest } from '@ahoo-wang/fetcher-react';\n *\n * const MyComponent = () => {\n * const [count, setCount] = useState(0);\n * const latestCount = useLatest(count);\n *\n * const handleAsync = async () => {\n * await someAsyncOperation();\n * console.log('Latest count:', latestCount.current); // Always the latest\n * };\n *\n * return (\n * <div>\n * <p>Count: {count}</p>\n * <button onClick={() => setCount(c => c + 1)}>Increment</button>\n * <button onClick={handleAsync}>Async Log</button>\n * </div>\n * );\n * };\n * ```\n */\nexport function useLatest<T>(value: T) {\n const ref = useRef(value);\n ref.current = value;\n return ref;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { useCallback, useMemo, useState } from 'react';\nimport { useMountedState } from 'react-use';\nimport { useLatest } from './useLatest';\n\n/**\n * Enumeration of possible promise execution states\n */\nexport enum PromiseStatus {\n IDLE = 'idle',\n LOADING = 'loading',\n SUCCESS = 'success',\n ERROR = 'error',\n}\n\nexport interface PromiseState<R, E = unknown> {\n /** Current status of the promise */\n status: PromiseStatus;\n /** Indicates if currently loading */\n loading: boolean;\n /** The result value */\n result: R | undefined;\n /** The error value */\n error: E | undefined;\n}\n\nexport interface PromiseStateCallbacks<R, E = unknown> {\n /** Callback invoked on success */\n onSuccess?: (result: R) => void;\n /** Callback invoked on error */\n onError?: (error: E) => void;\n}\n\n/**\n * Options for configuring usePromiseState behavior\n * @template R - The type of result\n *\n * @example\n * ```typescript\n * const options: UsePromiseStateOptions<string> = {\n * initialStatus: PromiseStatus.IDLE,\n * onSuccess: (result) => console.log('Success:', result),\n * onError: (error) => console.error('Error:', error),\n * };\n * ```\n */\nexport interface UsePromiseStateOptions<R, E = unknown> extends PromiseStateCallbacks<R, E> {\n /** Initial status, defaults to IDLE */\n initialStatus?: PromiseStatus;\n}\n\n/**\n * Return type for usePromiseState hook\n * @template R - The type of result\n */\nexport interface UsePromiseStateReturn<R, E = unknown>\n extends PromiseState<R, E> {\n /** Set status to LOADING */\n setLoading: () => void;\n /** Set status to SUCCESS with result */\n setSuccess: (result: R) => void;\n /** Set status to ERROR with error */\n setError: (error: E) => void;\n /** Set status to IDLE */\n setIdle: () => void;\n}\n\n/**\n * A React hook for managing promise state without execution logic\n * @template R - The type of result\n * @param options - Configuration options\n * @returns State management object\n *\n * @example\n * ```typescript\n * import { usePromiseState, PromiseStatus } from '@ahoo-wang/fetcher-react';\n *\n * function MyComponent() {\n * const { status, loading, result, error, setSuccess, setError, setIdle } = usePromiseState<string>();\n *\n * const handleSuccess = () => setSuccess('Data loaded');\n * const handleError = () => setError(new Error('Failed to load'));\n *\n * return (\n * <div>\n * <button onClick={handleSuccess}>Set Success</button>\n * <button onClick={handleError}>Set Error</button>\n * <button onClick={setIdle}>Reset</button>\n * <p>Status: {status}</p>\n * {loading && <p>Loading...</p>}\n * {result && <p>Result: {result}</p>}\n * {error && <p>Error: {error.message}</p>}\n * </div>\n * );\n * }\n * ```\n */\nexport function usePromiseState<R = unknown, E = unknown>(\n options?: UsePromiseStateOptions<R, E>,\n): UsePromiseStateReturn<R, E> {\n const [status, setStatus] = useState<PromiseStatus>(\n options?.initialStatus ?? PromiseStatus.IDLE,\n );\n const [result, setResult] = useState<R | undefined>(undefined);\n const [error, setErrorState] = useState<E | undefined>(undefined);\n const isMounted = useMountedState();\n const latestOptions = useLatest(options);\n const setLoadingFn = useCallback(() => {\n if (isMounted()) {\n setStatus(PromiseStatus.LOADING);\n setErrorState(undefined);\n }\n }, [isMounted]);\n\n const setSuccessFn = useCallback(\n (result: R) => {\n if (isMounted()) {\n setResult(result);\n setStatus(PromiseStatus.SUCCESS);\n setErrorState(undefined);\n latestOptions.current?.onSuccess?.(result);\n }\n },\n [isMounted, latestOptions],\n );\n\n const setErrorFn = useCallback(\n (error: E) => {\n if (isMounted()) {\n setErrorState(error);\n setStatus(PromiseStatus.ERROR);\n setResult(undefined);\n latestOptions.current?.onError?.(error);\n }\n },\n [isMounted, latestOptions],\n );\n\n const setIdleFn = useCallback(() => {\n if (isMounted()) {\n setStatus(PromiseStatus.IDLE);\n setErrorState(undefined);\n setResult(undefined);\n }\n }, [isMounted]);\n return useMemo(\n () => ({\n status,\n loading: status === PromiseStatus.LOADING,\n result,\n error,\n setLoading: setLoadingFn,\n setSuccess: setSuccessFn,\n setError: setErrorFn,\n setIdle: setIdleFn,\n }),\n [status, result, error, setLoadingFn, setSuccessFn, setErrorFn, setIdleFn],\n );\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { useRef, useCallback, useMemo } from 'react';\n\n/**\n * Return type for useRequestId hook\n */\nexport interface UseRequestIdReturn {\n /** Generate a new request ID and get the current one */\n generate: () => number;\n /** Get the current request ID without generating a new one */\n current: () => number;\n /** Check if a given request ID is the latest */\n isLatest: (requestId: number) => boolean;\n /** Invalidate current request ID (mark as stale) */\n invalidate: () => void;\n /** Reset request ID counter */\n reset: () => void;\n}\n\n/**\n * A React hook for managing request IDs and race condition protection\n *\n * @example\n * ```typescript\n * // Basic usage\n * const requestId = useRequestId();\n *\n * const execute = async () => {\n * const id = requestId.generate();\n *\n * try {\n * const result = await someAsyncOperation();\n *\n * // Check if this is still the latest request\n * if (requestId.isLatest(id)) {\n * setState(result);\n * }\n * } catch (error) {\n * if (requestId.isLatest(id)) {\n * setError(error);\n * }\n * }\n * };\n *\n * // Manual cancellation\n * const handleCancel = () => {\n * requestId.invalidate(); // All ongoing requests will be ignored\n * };\n * ```\n *\n * @example\n * ```typescript\n * // With async operation wrapper\n * const { execute, cancel } = useAsyncOperation(async (data) => {\n * return await apiCall(data);\n * }, [requestId]);\n * ```\n */\nexport function useRequestId(): UseRequestIdReturn {\n const requestIdRef = useRef<number>(0);\n\n const generate = useCallback((): number => {\n return ++requestIdRef.current;\n }, []);\n\n const current = useCallback((): number => {\n return requestIdRef.current;\n }, []);\n\n const isLatest = useCallback((requestId: number): boolean => {\n return requestId === requestIdRef.current;\n }, []);\n\n const invalidate = useCallback((): void => {\n requestIdRef.current++;\n }, []);\n\n const reset = useCallback((): void => {\n requestIdRef.current = 0;\n }, []);\n return useMemo(() => {\n return {\n generate,\n current,\n isLatest,\n invalidate,\n reset,\n };\n }, [generate, current, isLatest, invalidate, reset]);\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { useCallback, useMemo } from 'react';\nimport { useMountedState } from 'react-use';\nimport { usePromiseState, PromiseState, UsePromiseStateOptions } from './usePromiseState';\nimport { useRequestId } from './useRequestId';\n\n/**\n * Type definition for a function that returns a Promise\n * @template R - The type of value the promise will resolve to\n */\nexport type PromiseSupplier<R> = () => Promise<R>;\n\n/**\n * Interface defining the return type of useExecutePromise hook\n * @template R - The type of the result value\n */\nexport interface UseExecutePromiseReturn<R, E = unknown>\n extends PromiseState<R, E> {\n /** Function to execute a promise supplier or promise */\n execute: (input: PromiseSupplier<R> | Promise<R>) => Promise<R>;\n /** Function to reset the state to initial values */\n reset: () => void;\n}\n\n/**\n * A React hook for managing asynchronous operations with proper state handling\n * @template R - The type of the result value\n * @returns An object containing the current state and control functions\n *\n * @example\n * ```typescript\n * import { useExecutePromise } from '@ahoo-wang/fetcher-react';\n *\n * function MyComponent() {\n * const { loading, result, error, execute, reset } = useExecutePromise<string>();\n *\n * const fetchData = async () => {\n * const response = await fetch('/api/data');\n * return response.text();\n * };\n *\n * const handleFetch = () => {\n * execute(fetchData);\n * };\n *\n * const handleReset = () => {\n * reset();\n * };\n *\n * if (loading) return <div>Loading...</div>;\n * if (error) return <div>Error: {error.message}</div>;\n * return (\n * <div>\n * <button onClick={handleFetch}>Fetch Data</button>\n * <button onClick={handleReset}>Reset</button>\n * {result && <p>{result}</p>}\n * </div>\n * );\n * }\n * ```\n */\nexport function useExecutePromise<R = unknown, E = unknown>(options?: UsePromiseStateOptions<R, E>): UseExecutePromiseReturn<R, E> {\n const state = usePromiseState<R, E>(options);\n const isMounted = useMountedState();\n const requestId = useRequestId();\n\n /**\n * Execute a promise supplier or promise and manage its state\n * @param input - A function that returns a Promise or a Promise to be executed\n * @returns A Promise that resolves with the result of the executed promise\n */\n const execute = useCallback(\n async (input: PromiseSupplier<R> | Promise<R>): Promise<R> => {\n if (!isMounted()) {\n throw new Error('Component is unmounted');\n }\n const currentRequestId = requestId.generate();\n state.setLoading();\n try {\n const promise = typeof input === 'function' ? input() : input;\n const data = await promise;\n\n if (isMounted() && requestId.isLatest(currentRequestId)) {\n state.setSuccess(data);\n }\n return data;\n } catch (err) {\n if (isMounted() && requestId.isLatest(currentRequestId)) {\n state.setError(err as E);\n }\n throw err;\n }\n },\n [state, isMounted, requestId],\n );\n\n /**\n * Reset the state to initial values\n */\n const reset = useCallback(() => {\n if (isMounted()) {\n state.setIdle();\n }\n }, [state, isMounted]);\n\n return useMemo(\n () => ({\n loading: state.loading,\n result: state.result,\n error: state.error,\n execute,\n reset,\n status: state.status,\n }),\n [state.loading, state.result, state.error, execute, reset, state.status],\n );\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { useCallback, useSyncExternalStore } from 'react';\nimport { KeyStorage } from '@ahoo-wang/fetcher-storage';\n\n/**\n * A React hook that provides state management for a KeyStorage instance.\n * Subscribes to storage changes and returns the current value along with a setter function.\n *\n * @template T - The type of value stored in the key storage\n * @param keyStorage - The KeyStorage instance to subscribe to and manage\n * @returns A tuple containing the current stored value and a function to update it\n */\nexport function useKeyStorage<T>(\n keyStorage: KeyStorage<T>,\n): [T | null, (value: T) => void] {\n const subscribe = useCallback(\n (callback: () => void) => keyStorage.addListener(callback),\n [keyStorage],\n );\n const getSnapshot = useCallback(() => keyStorage.get(), [keyStorage]);\n const value = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n const setValue = useCallback(\n (value: T) => keyStorage.set(value),\n [keyStorage],\n );\n return [value, setValue];\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n fetcherRegistrar,\n FetcherCapable,\n FetchExchange,\n FetchRequest,\n getFetcher,\n RequestOptions,\n} from '@ahoo-wang/fetcher';\nimport { useRef, useCallback, useEffect, useState, useMemo } from 'react';\nimport { useMountedState } from 'react-use';\nimport {\n PromiseState,\n useLatest,\n usePromiseState,\n UsePromiseStateOptions,\n useRequestId,\n} from '../core';\n\n/**\n * Configuration options for the useFetcher hook.\n * Extends RequestOptions and FetcherCapable interfaces.\n */\nexport interface UseFetcherOptions<R, E = unknown>\n extends RequestOptions,\n FetcherCapable,\n UsePromiseStateOptions<R, E> {\n}\n\nexport interface UseFetcherReturn<R, E = unknown> extends PromiseState<R, E> {\n /** The FetchExchange object representing the ongoing fetch operation */\n exchange?: FetchExchange;\n execute: (request: FetchRequest) => Promise<void>;\n}\n\n/**\n * A React hook for managing asynchronous operations with proper state handling\n * @param options - Configuration options for the fetcher\n * @returns An object containing the current state and control functions\n *\n * @example\n * ```typescript\n * import { useFetcher } from '@ahoo-wang/fetcher-react';\n *\n * function MyComponent() {\n * const { loading, result, error, execute } = useFetcher<string>();\n *\n * const handleFetch = () => {\n * execute({ url: '/api/data', method: 'GET' });\n * };\n *\n * if (loading) return <div>Loading...</div>;\n * if (error) return <div>Error: {error.message}</div>;\n * return (\n * <div>\n * <button onClick={handleFetch}>Fetch Data</button>\n * {result && <p>{result}</p>}\n * </div>\n * );\n * }\n * ```\n */\nexport function useFetcher<R, E = unknown>(\n options?: UseFetcherOptions<R, E>,\n): UseFetcherReturn<R, E> {\n const { fetcher = fetcherRegistrar.default } = options || {};\n const state = usePromiseState<R, E>(options);\n const [exchange, setExchange] = useState<FetchExchange | undefined>(\n undefined,\n );\n const isMounted = useMountedState();\n const abortControllerRef = useRef<AbortController | undefined>();\n const requestId = useRequestId();\n const latestOptions = useLatest(options);\n const currentFetcher = getFetcher(fetcher);\n /**\n * Execute the fetch operation.\n * Cancels any ongoing fetch before starting a new one.\n */\n const execute = useCallback(\n async (request: FetchRequest) => {\n if (abortControllerRef.current) {\n abortControllerRef.current.abort();\n }\n abortControllerRef.current =\n request.abortController ?? new AbortController();\n request.abortController = abortControllerRef.current;\n const currentRequestId = requestId.generate();\n state.setLoading();\n try {\n const exchange = await currentFetcher.exchange(\n request,\n latestOptions.current,\n );\n if (isMounted() && requestId.isLatest(currentRequestId)) {\n setExchange(exchange);\n }\n const result = await exchange.extractResult<R>();\n if (isMounted() && requestId.isLatest(currentRequestId)) {\n state.setSuccess(result);\n }\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') {\n if (isMounted()) {\n state.setIdle();\n }\n return;\n }\n if (isMounted() && requestId.isLatest(currentRequestId)) {\n state.setError(error as E);\n }\n } finally {\n if (abortControllerRef.current === request.abortController) {\n abortControllerRef.current = undefined;\n }\n }\n },\n [currentFetcher, isMounted, latestOptions, state, requestId],\n );\n\n useEffect(() => {\n return () => {\n abortControllerRef.current?.abort();\n abortControllerRef.current = undefined;\n };\n }, []);\n return useMemo(\n () => ({\n ...state,\n exchange,\n execute,\n }),\n [state, exchange, execute],\n );\n}\n"],"names":["useMountedState","mountedRef","useRef","get","useCallback","useEffect","useLatest","value","ref","PromiseStatus","usePromiseState","options","status","setStatus","useState","result","setResult","error","setErrorState","isMounted","latestOptions","setLoadingFn","setSuccessFn","setErrorFn","setIdleFn","useMemo","useRequestId","requestIdRef","generate","current","isLatest","requestId","invalidate","reset","useExecutePromise","state","execute","input","currentRequestId","data","err","useKeyStorage","keyStorage","subscribe","callback","getSnapshot","useSyncExternalStore","setValue","useFetcher","fetcher","fetcherRegistrar","exchange","setExchange","abortControllerRef","currentFetcher","getFetcher","request"],"mappings":"uUACe,SAASA,GAAkB,CACtC,IAAIC,EAAaC,EAAAA,OAAO,EAAK,EACzBC,EAAMC,EAAAA,YAAY,UAAY,CAAE,OAAOH,EAAW,OAAS,EAAG,EAAE,EACpEI,OAAAA,EAAAA,UAAU,UAAY,CAClB,OAAAJ,EAAW,QAAU,GACd,UAAY,CACfA,EAAW,QAAU,EACzB,CACJ,EAAG,CAAA,CAAE,EACEE,CACX,CCkCO,SAASG,EAAaC,EAA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AASO,CAAgB,GACpDc,EAAYD,CAAQ,EAEtB,MAAMpC,EAAS,MAAMoC,EAAS,cAAA,EAC1BhC,EAAA,GAAeY,EAAU,SAASO,CAAgB,GACpDH,EAAM,WAAWpB,CAAM,CAE3B,OAASE,EAAO,CACd,GAAIA,aAAiB,OAASA,EAAM,OAAS,aAAc,CACrDE,KACFgB,EAAM,QAAA,EAER,MACF,CACIhB,EAAA,GAAeY,EAAU,SAASO,CAAgB,GACpDH,EAAM,SAASlB,CAAU,CAE7B,QAAA,CACMoC,EAAmB,UAAYG,EAAQ,kBACzCH,EAAmB,QAAU,OAEjC,CACF,EACA,CAACC,EAAgBnC,EAAWC,EAAee,EAAOJ,CAAS,CAAA,EAG7D1B,OAAAA,EAAAA,UAAU,IACD,IAAM,CACXgD,EAAmB,SAAS,MAAA,EAC5BA,EAAmB,QAAU,MAC/B,EACC,CAAA,CAAE,EACE5B,EAAAA,QACL,KAAO,CACL,GAAGU,EACH,SAAAgB,EACA,QAAAf,CAAA,GAEF,CAACD,EAAOgB,EAAUf,CAAO,CAAA,CAE7B","x_google_ignoreList":[0]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ahoo-wang/fetcher-react",
3
- "version": "2.6.2",
3
+ "version": "2.6.3",
4
4
  "description": "React integration for Fetcher HTTP client. Provides React Hooks and components for seamless data fetching with automatic re-rendering and loading states.",
5
5
  "keywords": [
6
6
  "fetch",