@@ -172,39 +172,40 @@ export function useDataState<T, A extends any[] = any[]>(
172172// and attaches it to the DataState's internal DataRoot value that is
173173// tracked and updated with `useState`:
174174function useFetcher < T , A extends any [ ] = any [ ] > (
175- fetcher : ( ...args : A ) => Promise < T > ,
175+ fetcher : ( ...args : A ) => Promise < T > | Response ,
176176 args : A ,
177177 setRoot : Dispatch < SetStateAction < DataRoot < T > > > ,
178- ) : ( ) => Promise < any > {
178+ ) : ( ) => Promise < T | undefined > {
179179 return useCallback ( async ( ) => {
180180 // console.log('Fetch triggered with args: ', args);
181181 // Skip fetching if one of the arguments is still undefined:
182182 if ( args ?. some ( arg => arg === undefined ) ) return ;
183183
184- let response ;
185-
186184 try {
187- response = await fetcher ( ...args ) ;
188- // console.log('response = ', response);
189-
190- // If the function is fetch, call `.json()`:
191- if ( response instanceof Response ) {
192- if ( ! response . ok ) throw new Error ( `Fetch response NOT OK, status: ${ response . status } ` ) ;
193- const json = await response . json ( ) ;
194- if ( 'result' in json ) response = json . result ;
195- else response = json ;
196- }
185+ let response = await fetcher ( ...args ) ;
197186 if ( ! response ) throw new Error ( 'Empty response' ) ;
198- setRoot ( DataState . value ( response ) ) ;
187+
188+ const typedResponse = response as T ;
189+ setRoot ( DataState . value ( typedResponse ) ) ;
190+ return typedResponse ;
199191 } catch ( err ) {
200192 setRoot ( DataState . error ( err ) ) ;
201193 }
202-
203- // console.log('response = ', response);
204- return response ;
205194 } , [ fetcher , args , setRoot ] ) ;
206195}
207196
197+ // To be used as a wrapper for fetch() inside useDataState inline fetcher definition:
198+ // (This allows the types to match with the DataState's, instead of returning a fetch Response type)
199+ export async function fetchJson < T > ( url : string ) : Promise < T > {
200+ const response = await fetch ( url ) ;
201+ if ( ! response . ok ) throw new Error ( `Fetch failed, status: ${ response . status } ` ) ;
202+ const json = await response . json ( ) ;
203+ const result = 'result' in json ? json . result : json ;
204+ if ( ! result ) throw new Error ( 'Empty json response' ) ;
205+
206+ return result as T ;
207+ }
208+
208209// Hook that memoizes the argument array to prevent a new array
209210// from being created on every render:
210211// (For inline use in `useDataState()` or `DataState.Init()` calls)
0 commit comments