@@ -372,7 +372,6 @@ const useFetchReducer = (state, action) => {
372
372
373
373
export function useFetch ( url , options ) {
374
374
const cacheRef = React . useRef ( { } ) ;
375
- const ignoreRef = React . useRef ( false ) ;
376
375
377
376
const [ state , dispatch ] = React . useReducer (
378
377
useFetchReducer ,
@@ -386,15 +385,18 @@ export function useFetch(url, options) {
386
385
React . useEffect ( ( ) => {
387
386
if ( typeof url !== "string" ) return ;
388
387
388
+ let ignore = false ;
389
+
389
390
const fetchData = async ( ) => {
390
- dispatch ( { type : "loading" } ) ;
391
391
const cachedResponse = cacheRef . current [ url ] ;
392
392
393
393
if ( cachedResponse ) {
394
394
dispatch ( { type : "fetched" , payload : cachedResponse } ) ;
395
395
return ;
396
396
}
397
397
398
+ dispatch ( { type : "loading" } ) ;
399
+
398
400
try {
399
401
const res = await onFetch ( url ) ;
400
402
@@ -405,21 +407,20 @@ export function useFetch(url, options) {
405
407
const json = await res . json ( ) ;
406
408
cacheRef . current [ url ] = json ;
407
409
408
- if ( ignoreRef . current === false ) {
410
+ if ( ignore === false ) {
409
411
dispatch ( { type : "fetched" , payload : json } ) ;
410
412
}
411
413
} catch ( e ) {
412
- if ( ignoreRef . current === false ) {
414
+ if ( ignore === false ) {
413
415
dispatch ( { type : "error" , payload : e } ) ;
414
416
}
415
417
}
416
418
} ;
417
419
418
- ignoreRef . current = false ;
419
420
fetchData ( ) ;
420
421
421
422
return ( ) => {
422
- ignoreRef . current = true ;
423
+ ignore = true ;
423
424
} ;
424
425
} , [ url ] ) ;
425
426
0 commit comments