Skip to content

Commit f66f9e9

Browse files
committed
3.3.0: reset() + useCallback
1 parent 20fb503 commit f66f9e9

File tree

1 file changed

+26
-4
lines changed

1 file changed

+26
-4
lines changed

src/index.ts

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useEffect, useRef, useState } from 'react';
1+
import { useCallback, useEffect, useRef, useState } from 'react';
22

33
export type AsyncState<R> = {
44
loading: boolean;
@@ -63,6 +63,7 @@ const normalizeOptions = <R>(
6363
type UseAsyncStateResult<R> = {
6464
value: AsyncState<R>;
6565
set: (value: AsyncState<R>) => void;
66+
reset: () => void;
6667
setLoading: () => void;
6768
setResult: (r: R) => void;
6869
setError: (e: Error) => void;
@@ -73,12 +74,33 @@ const useAsyncState = <R extends {}>(
7374
const [value, setValue] = useState<AsyncState<R>>(() =>
7475
options.initialState()
7576
);
77+
78+
const reset = useCallback(() => setValue(options.initialState()), [
79+
setValue,
80+
options,
81+
]);
82+
83+
const setLoading = useCallback(() => setValue(options.setLoading(value)), [
84+
value,
85+
setValue,
86+
]);
87+
const setResult = useCallback(
88+
(result: R) => setValue(options.setResult(result, value)),
89+
[value, setValue]
90+
);
91+
92+
const setError = useCallback(
93+
(error: Error) => setValue(options.setError(error, value)),
94+
[value, setValue]
95+
);
96+
7697
return {
7798
value,
7899
set: setValue,
79-
setLoading: () => setValue(options.setLoading(value)),
80-
setResult: result => setValue(options.setResult(result, value)),
81-
setError: error => setValue(options.setError(error, value)),
100+
reset,
101+
setLoading,
102+
setResult,
103+
setError,
82104
};
83105
};
84106

0 commit comments

Comments
 (0)