File tree Expand file tree Collapse file tree 1 file changed +16
-7
lines changed
Expand file tree Collapse file tree 1 file changed +16
-7
lines changed Original file line number Diff line number Diff line change @@ -99,21 +99,30 @@ export const useWorker = <TArgs extends readonly any[], TRet>(
9999 error : Error | undefined ;
100100 callback : ( ...args : TArgs ) => Promise < TRet | undefined > ;
101101} => {
102- const [ isLoading , setIsLoading ] = useState < boolean > ( false ) ;
103- const [ error , setError ] = useState < Error | undefined > ( undefined ) ;
102+ const [ { isLoading, error } , setState ] = useState ( {
103+ isLoading : false ,
104+ error : undefined as Error | undefined ,
105+ } ) ;
106+
107+ const setError = useCallback ( ( error : Error | undefined ) => {
108+ setState ( s => ( { ...s , error } ) ) ;
109+ } , [ ] ) ;
110+
111+ const setIsLoading = useCallback ( ( isLoading : boolean ) => {
112+ setState ( s => ( { ...s , isLoading } ) ) ;
113+ } , [ ] ) ;
114+
104115 const callback = useCallback ( async ( ...args : TArgs ) : Promise <
105116 TRet | undefined
106117 > => {
107118 try {
108119 setIsLoading ( true ) ;
109120 const result = await worker ( ...args ) ;
110- setIsLoading ( false ) ;
111- setError ( undefined ) ;
121+ setState ( { isLoading : false , error : undefined } ) ;
112122
113123 return result ;
114- } catch ( e ) {
115- setIsLoading ( false ) ;
116- setError ( e ) ;
124+ } catch ( error ) {
125+ setState ( { isLoading : false , error } ) ;
117126 }
118127 } , dependencies ) ;
119128
You can’t perform that action at this time.
0 commit comments