@pushwoosh/kit-helpers 4.5.0 → 4.6.1
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/hooks/useAsyncFn.d.ts +4 -1
- package/hooks/useAsyncFn.js +8 -4
- package/package.json +1 -1
package/hooks/useAsyncFn.d.ts
CHANGED
|
@@ -18,9 +18,12 @@ export type AsyncState<T> = {
|
|
|
18
18
|
value: T;
|
|
19
19
|
};
|
|
20
20
|
type StateFromFunctionReturningPromise<T extends FunctionReturningPromise> = AsyncState<PromiseType<ReturnType<T>>>;
|
|
21
|
+
export type CallbackParams = {
|
|
22
|
+
reset?: boolean;
|
|
23
|
+
};
|
|
21
24
|
export type AsyncFnReturn<T extends FunctionReturningPromise = FunctionReturningPromise> = [
|
|
22
25
|
StateFromFunctionReturningPromise<T>,
|
|
23
|
-
T
|
|
26
|
+
(p?: CallbackParams) => ReturnType<T>
|
|
24
27
|
];
|
|
25
28
|
export default function useAsyncFn<T extends FunctionReturningPromise>(fn: T, deps?: DependencyList, initialState?: StateFromFunctionReturningPromise<T> | (() => StateFromFunctionReturningPromise<T>)): AsyncFnReturn<T>;
|
|
26
29
|
export {};
|
package/hooks/useAsyncFn.js
CHANGED
|
@@ -7,17 +7,21 @@ export default function useAsyncFn(fn, deps = [], initialState = getDefaultState
|
|
|
7
7
|
const lastCallId = useRef(0);
|
|
8
8
|
const isMounted = useMountedState();
|
|
9
9
|
const [state, setState] = useState(initialState);
|
|
10
|
-
const callback = useCallback((
|
|
10
|
+
const callback = useCallback(({
|
|
11
|
+
reset
|
|
12
|
+
} = {}) => {
|
|
11
13
|
// eslint-disable-next-line no-plusplus
|
|
12
14
|
const callId = ++lastCallId.current;
|
|
13
15
|
const canSet = () => isMounted() && callId === lastCallId.current;
|
|
14
16
|
if (canSet()) {
|
|
15
|
-
setState(prevState =>
|
|
17
|
+
setState(prevState => reset ? {
|
|
18
|
+
loading: true
|
|
19
|
+
} : {
|
|
16
20
|
...prevState,
|
|
17
21
|
loading: true
|
|
18
|
-
})
|
|
22
|
+
});
|
|
19
23
|
}
|
|
20
|
-
return fn(
|
|
24
|
+
return fn().then(value => {
|
|
21
25
|
if (canSet()) {
|
|
22
26
|
setState({
|
|
23
27
|
value,
|