File tree Expand file tree Collapse file tree 3 files changed +26
-2
lines changed
Expand file tree Collapse file tree 3 files changed +26
-2
lines changed Original file line number Diff line number Diff line change 11{
22 "name" : " react-fetch-hook" ,
3- "version" : " 1.2.1 " ,
3+ "version" : " 1.2.2 " ,
44 "description" : " React fetch hook" ,
55 "main" : " ./dist/index.js" ,
66 "scripts" : {
Original file line number Diff line number Diff line change @@ -79,4 +79,23 @@ describe("useFetch", () => {
7979 expect ( fetch . mock . calls [ 0 ] [ 1 ] ) . toMatchObject ( { ...options } ) ;
8080 } ) ;
8181 } ) ;
82+
83+ it ( "error on throw error" , async ( ) => {
84+ fetch . mockReject ( new Error ( "fake error message" ) ) ;
85+
86+ const Component = ( ) => {
87+ const result = useFetch ( "https://google.com" ) ;
88+ return ( result . error && result . error . message ) || "text" ;
89+ } ;
90+
91+ const { container, rerender } = render ( < Component /> ) ;
92+
93+ await wait ( ( ) => {
94+ rerender ( < Component /> ) ;
95+
96+ expect ( fetch . mock . calls . length ) . toEqual ( 1 ) ;
97+ expect ( container ) . toHaveTextContent ( "fake error message" ) ;
98+ expect ( fetch . mock . calls [ 0 ] [ 0 ] ) . toEqual ( "https://google.com" ) ;
99+ } ) ;
100+ } ) ;
82101} ) ;
Original file line number Diff line number Diff line change @@ -11,7 +11,12 @@ export function useFetch<T>(
1111 path : RequestInfo ,
1212 options ?: { ...RequestOptions , formatter ?: Response => Promise < T > }
1313) : TUseFetchResult < T > {
14- const defaultFormatter = response => response . json ( ) ;
14+ const defaultFormatter = response => {
15+ if ( ! response . ok ) {
16+ throw Error ( response . statusText ) ;
17+ }
18+ return response . json ( ) ;
19+ } ;
1520 const fetchInstance = formatter => ( path , options ) => {
1621 return fetch ( path , options ) . then ( ( typeof formatter === "function" && formatter ) || defaultFormatter ) ;
1722 } ;
You can’t perform that action at this time.
0 commit comments