1
- import { useEffect , useRef , useState } from 'react' ;
1
+ import { useCallback , useEffect , useRef , useState } from 'react' ;
2
2
3
3
export type AsyncState < R > = {
4
4
loading : boolean ;
@@ -63,6 +63,7 @@ const normalizeOptions = <R>(
63
63
type UseAsyncStateResult < R > = {
64
64
value : AsyncState < R > ;
65
65
set : ( value : AsyncState < R > ) => void ;
66
+ reset : ( ) => void ;
66
67
setLoading : ( ) => void ;
67
68
setResult : ( r : R ) => void ;
68
69
setError : ( e : Error ) => void ;
@@ -73,12 +74,33 @@ const useAsyncState = <R extends {}>(
73
74
const [ value , setValue ] = useState < AsyncState < R > > ( ( ) =>
74
75
options . initialState ( )
75
76
) ;
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
+
76
97
return {
77
98
value,
78
99
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,
82
104
} ;
83
105
} ;
84
106
0 commit comments