-
-
Save aishwarya257/91b330217707bafe9742984f7661adcc to your computer and use it in GitHub Desktop.
Cancellable fetch function with AbortController
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function useCancelableFetch<T = unknown>(initialData: Record<string, unknown> = {}) { | |
const [state, unsafeDispatch] = useReducer< | |
Reducer<FetchState<T>, FetchAction<T>> | |
>(fetchReducer, { | |
status: FETCH_STATUS.idle, | |
data: null, | |
...initialData | |
}); | |
const controllerRef = useRef(new AbortController()); | |
useEffect(() => { | |
const controller = controllerRef.current; | |
return () => { | |
controller.abort(); | |
} | |
}, []) | |
const dispatch = useSafeDispatch<FetchAction<T>>(unsafeDispatch); | |
const call = useCallback( | |
async (url) => { | |
const controller = controllerRef.current; | |
dispatch({ type: FETCH_STATUS.pending }); | |
try { | |
const response = await fetch(url, {signal: controller.signal}); | |
const data = await response.json(); | |
dispatch({type: FETCH_STATUS.resolved, data}) | |
} catch(e) { | |
console.log(e) | |
} | |
}, | |
[dispatch] | |
); | |
return [state, call] as const; | |
} | |
export default useCancelableFetch; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment