Last active
November 23, 2022 09:32
-
-
Save mlnor27/27bbb92c50be17c3dad9cc3b3a305d96 to your computer and use it in GitHub Desktop.
"useFetch" - A little React hook to handle HTTP request
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
import { useEffect, useReducer, useRef } from "react"; | |
const initialState = { | |
isLoading: false, | |
data: null, | |
err: null, | |
cancel: () => {} | |
}; | |
const reducer = (state, { type, payload }) => { | |
switch (type) { | |
case "START": | |
return { | |
...initialState, | |
isLoading: true, | |
cancel: payload | |
}; | |
case "SUCCESS": | |
return { | |
...initialState, | |
data: payload | |
}; | |
case "CANCELLED": | |
return { ...initialState }; | |
case "FAILED": | |
return { | |
...initialState, | |
err: payload | |
}; | |
default: | |
return state; | |
} | |
}; | |
const fetchOptions = {}; | |
/** | |
* A React hook to easily handle HTTP request | |
* @param {string} url URL requested | |
* @param {object} options Fetch API options | |
* @returns {object} | |
* @example Inside a React function component : | |
* const { isLoading, data, err, cancel } = useFetch(URL); | |
*/ | |
const useFetch = (url, options = fetchOptions) => { | |
const [state, dispatch] = useReducer(reducer, initialState); | |
const aborted = useRef(false); | |
useEffect(() => { | |
if (!url) return; | |
const controller = | |
typeof AbortController !== "undefined" ? new AbortController() : null; | |
const cancel = () => { | |
if (controller) { | |
aborted.current = true; | |
controller.abort(); | |
} | |
}; | |
(async () => { | |
dispatch({ | |
type: "START", | |
payload: cancel | |
}); | |
try { | |
const response = await fetch(url, { | |
...options, | |
signal: controller && controller.signal | |
}); | |
const result = await response.json(); | |
dispatch({ | |
type: "SUCCESS", | |
payload: result | |
}); | |
} catch (e) { | |
if (aborted.current) { | |
aborted.current = false; | |
dispatch({ type: "CANCELLED" }); | |
} else { | |
dispatch({ | |
type: "FAILED", | |
payload: e | |
}); | |
} | |
} | |
})(); | |
return cancel; | |
}, [url, options]); | |
return state; | |
}; | |
export default useFetch; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment