| 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; |
| 78 | if (cancelRequest.current) return; |
| 79 | |
| 80 | dispatch({ type: "fetched", payload: dataOrError }); |
| 81 | } catch (error) { |
| 82 | if (cancelRequest.current) return; |
| 83 | |
| 84 | dispatch({ type: "error", payload: error as Error }); |
| 85 | } |
| 86 | }; |
| 87 | |
| 88 | void fetchData(); |
| 89 | |