|
| 1 | +import { useEffect, useReducer, useRef } from "react"; |
| 2 | +import axios, { AxiosRequestConfig } from "axios"; |
| 3 | +// State & hook output |
| 4 | + |
| 5 | +interface Error { |
| 6 | + message: string, |
| 7 | + status: number, |
| 8 | +} |
| 9 | + |
| 10 | +interface State<T> { |
| 11 | + status: "init" | "fetching" | "error" | "fetched"; |
| 12 | + data?: T; |
| 13 | + error?: Error; |
| 14 | +} |
| 15 | +interface Cache<T> { |
| 16 | + [url: string]: T; |
| 17 | +} |
| 18 | + |
| 19 | + |
| 20 | +// discriminated union type |
| 21 | +type Action<T> = |
| 22 | + | { type: "request" } |
| 23 | + | { type: "success"; payload: T } |
| 24 | + | { type: "failure"; payload: Error }; |
| 25 | +function useFetch<T = unknown>( |
| 26 | + url?: string, |
| 27 | + options?: AxiosRequestConfig |
| 28 | +): State<T> { |
| 29 | + const cache = useRef<Cache<T>>({}); |
| 30 | + const cancelRequest = useRef<boolean>(false); |
| 31 | + const initialState: State<T> = { |
| 32 | + status: "init", |
| 33 | + error: undefined, |
| 34 | + data: undefined, |
| 35 | + }; |
| 36 | + // Keep state logic separated |
| 37 | + const fetchReducer = (state: State<T>, action: Action<T>): State<T> => { |
| 38 | + switch (action.type) { |
| 39 | + case "request": |
| 40 | + return { ...initialState, status: "fetching" }; |
| 41 | + case "success": |
| 42 | + return { ...initialState, status: "fetched", data: action.payload }; |
| 43 | + case "failure": |
| 44 | + return { ...initialState, status: "error", error: action.payload }; |
| 45 | + default: |
| 46 | + return state; |
| 47 | + } |
| 48 | + }; |
| 49 | + const [state, dispatch] = useReducer(fetchReducer, initialState); |
| 50 | + useEffect(() => { |
| 51 | + if (!url) { |
| 52 | + return; |
| 53 | + } |
| 54 | + const fetchData = async () => { |
| 55 | + dispatch({ type: "request" }); |
| 56 | + if (cache.current[url]) { |
| 57 | + dispatch({ type: "success", payload: cache.current[url] }); |
| 58 | + } else { |
| 59 | + try { |
| 60 | + const response = await axios(url, options); |
| 61 | + cache.current[url] = response.data; |
| 62 | + if (cancelRequest.current) return; |
| 63 | + dispatch({ type: "success", payload: response.data }); |
| 64 | + } catch (error) { |
| 65 | + if (cancelRequest.current) return; |
| 66 | + console.log(error.response); |
| 67 | + dispatch({ type: "failure", payload: { message: error.message, status: error.response.status }}); |
| 68 | + } |
| 69 | + } |
| 70 | + }; |
| 71 | + fetchData(); |
| 72 | + return () => { |
| 73 | + cancelRequest.current = true; |
| 74 | + }; |
| 75 | + // eslint-disable-next-line react-hooks/exhaustive-deps |
| 76 | + }, [url]); |
| 77 | + return state; |
| 78 | +} |
| 79 | +export default useFetch; |
0 commit comments