Skip to content

Commit d972970

Browse files
committed
Refactor useFetch
1 parent 3b99428 commit d972970

File tree

1 file changed

+24
-21
lines changed

1 file changed

+24
-21
lines changed

index.js

Lines changed: 24 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -352,31 +352,34 @@ export function useFavicon(url) {
352352
}, [url]);
353353
}
354354

355+
const useFetchInitialState = {
356+
error: undefined,
357+
data: undefined,
358+
};
359+
360+
const useFetchReducer = (state, action) => {
361+
switch (action.type) {
362+
case "loading":
363+
return { ...useFetchInitialState };
364+
case "fetched":
365+
return { ...useFetchInitialState, data: action.payload };
366+
case "error":
367+
return { ...useFetchInitialState, error: action.payload };
368+
default:
369+
return state;
370+
}
371+
};
372+
355373
export function useFetch(url, options) {
356374
const cacheRef = React.useRef({});
357375
const ignoreRef = React.useRef(false);
358376

359-
const initialState = {
360-
error: undefined,
361-
data: undefined,
362-
};
363-
364-
const reducer = (state, action) => {
365-
switch (action.type) {
366-
case "loading":
367-
return { ...initialState };
368-
case "fetched":
369-
return { ...initialState, data: action.payload };
370-
case "error":
371-
return { ...initialState, error: action.payload };
372-
default:
373-
return state;
374-
}
375-
};
376-
377-
const [state, dispatch] = React.useReducer(reducer, initialState);
377+
const [state, dispatch] = React.useReducer(
378+
useFetchReducer,
379+
useFetchInitialState
380+
);
378381

379-
const onFetch = React.useEffectEvent(() => {
382+
const onFetch = React.useEffectEvent((url) => {
380383
return fetch(url, options);
381384
});
382385

@@ -393,7 +396,7 @@ export function useFetch(url, options) {
393396
}
394397

395398
try {
396-
const res = await onFetch();
399+
const res = await onFetch(url);
397400

398401
if (!res.ok) {
399402
throw new Error(res.statusText);

0 commit comments

Comments
 (0)