( fetch: FetchEsque, url?: string, options?: RequestInit, )
| 18 | | { type: "error"; payload: Error }; |
| 19 | |
| 20 | function useFetch<T = unknown>( |
| 21 | fetch: FetchEsque, |
| 22 | url?: string, |
| 23 | options?: RequestInit, |
| 24 | ): State<T> { |
| 25 | const cache = useRef<Cache<T>>({}); |
| 26 | |
| 27 | // Used to prevent state update if the component is unmounted |
| 28 | const cancelRequest = useRef<boolean>(false); |
| 29 | |
| 30 | const initialState: State<T> = { |
| 31 | error: undefined, |
| 32 | data: undefined, |
| 33 | }; |
| 34 | |
| 35 | // Keep state logic separated |
| 36 | const fetchReducer = (state: State<T>, action: Action<T>): State<T> => { |
| 37 | switch (action.type) { |
| 38 | case "loading": |
| 39 | return { ...initialState }; |
| 40 | case "fetched": |
| 41 | return { ...initialState, data: action.payload }; |
| 42 | case "error": |
| 43 | return { ...initialState, error: action.payload }; |
| 44 | default: |
| 45 | return state; |
| 46 | } |
| 47 | }; |
| 48 | |
| 49 | const [state, dispatch] = useReducer(fetchReducer, initialState); |
| 50 | |
| 51 | useEffect(() => { |
| 52 | // Do nothing if the url is not given |
| 53 | if (!url) return; |
| 54 | |
| 55 | cancelRequest.current = false; |
| 56 | |
| 57 | const fetchData = async () => { |
| 58 | dispatch({ type: "loading" }); |
| 59 | |
| 60 | // If a cache exists for this url, return it |
| 61 | if (cache.current[url]) { |
| 62 | dispatch({ type: "fetched", payload: cache.current[url] }); |
| 63 | return; |
| 64 | } |
| 65 | |
| 66 | try { |
| 67 | const response = await fetch(url, options); |
| 68 | if (!response.ok) { |
| 69 | throw new Error(response.statusText); |
| 70 | } |
| 71 | |
| 72 | const dataOrError = await safeParseJSON<T>(response); |
| 73 | if (dataOrError instanceof Error) { |
| 74 | throw dataOrError; |
| 75 | } |
| 76 | |
| 77 | cache.current[url] = dataOrError; |
no test coverage detected