Skip to content

Commit 5f767f0

Browse files
committed
Fix useFetch
1 parent d972970 commit 5f767f0

File tree

1 file changed

+7
-6
lines changed

1 file changed

+7
-6
lines changed

index.js

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -372,7 +372,6 @@ const useFetchReducer = (state, action) => {
372372

373373
export function useFetch(url, options) {
374374
const cacheRef = React.useRef({});
375-
const ignoreRef = React.useRef(false);
376375

377376
const [state, dispatch] = React.useReducer(
378377
useFetchReducer,
@@ -386,15 +385,18 @@ export function useFetch(url, options) {
386385
React.useEffect(() => {
387386
if (typeof url !== "string") return;
388387

388+
let ignore = false;
389+
389390
const fetchData = async () => {
390-
dispatch({ type: "loading" });
391391
const cachedResponse = cacheRef.current[url];
392392

393393
if (cachedResponse) {
394394
dispatch({ type: "fetched", payload: cachedResponse });
395395
return;
396396
}
397397

398+
dispatch({ type: "loading" });
399+
398400
try {
399401
const res = await onFetch(url);
400402

@@ -405,21 +407,20 @@ export function useFetch(url, options) {
405407
const json = await res.json();
406408
cacheRef.current[url] = json;
407409

408-
if (ignoreRef.current === false) {
410+
if (ignore === false) {
409411
dispatch({ type: "fetched", payload: json });
410412
}
411413
} catch (e) {
412-
if (ignoreRef.current === false) {
414+
if (ignore === false) {
413415
dispatch({ type: "error", payload: e });
414416
}
415417
}
416418
};
417419

418-
ignoreRef.current = false;
419420
fetchData();
420421

421422
return () => {
422-
ignoreRef.current = true;
423+
ignore = true;
423424
};
424425
}, [url]);
425426

0 commit comments

Comments
 (0)