|
| 1 | +import React, { |
| 2 | + createContext, useCallback, useContext, useEffect, useRef, useState, |
| 3 | +} from 'react'; |
| 4 | + |
| 5 | +const CACHE_TTL_MS = 30 * 60 * 1000; |
| 6 | +const PRUNE_INTERVAL_MS = 5 * 60 * 1000; |
| 7 | + |
| 8 | +const QueryCacheContext = createContext(null); |
| 9 | + |
| 10 | +export const QueryCacheProvider = ({ children }) => { |
| 11 | + const [cache, setCache] = useState(new Map()); |
| 12 | + |
| 13 | + const get = useCallback((key) => { |
| 14 | + const entry = cache.get(key); |
| 15 | + if (!entry) return undefined; |
| 16 | + |
| 17 | + const now = Date.now(); |
| 18 | + if (now - entry.timestamp > CACHE_TTL_MS) { |
| 19 | + setCache((prev) => { |
| 20 | + const next = new Map(prev); |
| 21 | + next.delete(key); |
| 22 | + return next; |
| 23 | + }); |
| 24 | + return undefined; |
| 25 | + } |
| 26 | + |
| 27 | + return entry.data; |
| 28 | + }, [cache]); |
| 29 | + |
| 30 | + const set = useCallback((key, value) => { |
| 31 | + setCache((prev) => { |
| 32 | + const next = new Map(prev); |
| 33 | + next.set(key, { data: value, timestamp: Date.now() }); |
| 34 | + return next; |
| 35 | + }); |
| 36 | + }, []); |
| 37 | + |
| 38 | + useEffect(() => { |
| 39 | + const interval = setInterval(() => { |
| 40 | + setCache((prev) => { |
| 41 | + const now = Date.now(); |
| 42 | + const next = new Map(prev); |
| 43 | + // eslint-disable-next-line no-restricted-syntax |
| 44 | + for (const [key, entry] of next.entries()) { |
| 45 | + if (now - entry.timestamp > CACHE_TTL_MS) { |
| 46 | + next.delete(key); |
| 47 | + } |
| 48 | + } |
| 49 | + return next; |
| 50 | + }); |
| 51 | + }, PRUNE_INTERVAL_MS); |
| 52 | + |
| 53 | + return () => clearInterval(interval); |
| 54 | + }, []); |
| 55 | + |
| 56 | + return ( |
| 57 | + <QueryCacheContext.Provider value={{ get, set }}> |
| 58 | + {children} |
| 59 | + </QueryCacheContext.Provider> |
| 60 | + ); |
| 61 | +}; |
| 62 | + |
| 63 | +export const useQuery = ({ |
| 64 | + queryFn, |
| 65 | + queryKey, |
| 66 | + debounceMs = 0, |
| 67 | + keepStaleData = false, |
| 68 | +}) => { |
| 69 | + const [data, setData] = useState(null); |
| 70 | + const [isLoading, setIsLoading] = useState(true); |
| 71 | + const [error, setError] = useState(null); |
| 72 | + |
| 73 | + const cache = useContext(QueryCacheContext); |
| 74 | + if (!cache) throw new Error('You must use `useQuery` hook within `QueryCacheProvider`'); |
| 75 | + |
| 76 | + const timeoutRef = useRef(null); |
| 77 | + const abortControllerRef = useRef(null); |
| 78 | + |
| 79 | + useEffect(() => { |
| 80 | + let ignore = false; |
| 81 | + |
| 82 | + if (timeoutRef.current) { |
| 83 | + clearTimeout(timeoutRef.current); |
| 84 | + } |
| 85 | + |
| 86 | + if (abortControllerRef.current) { |
| 87 | + abortControllerRef.current.abort(); |
| 88 | + } |
| 89 | + |
| 90 | + timeoutRef.current = setTimeout(() => { |
| 91 | + (async () => { |
| 92 | + if (!keepStaleData) setData(null); |
| 93 | + setIsLoading(true); |
| 94 | + setError(null); |
| 95 | + |
| 96 | + const cachedData = cache.get(queryKey); |
| 97 | + if (cachedData) { |
| 98 | + setData(cachedData); |
| 99 | + setIsLoading(false); |
| 100 | + return; |
| 101 | + } |
| 102 | + |
| 103 | + const controller = new AbortController(); |
| 104 | + abortControllerRef.current = controller; |
| 105 | + |
| 106 | + try { |
| 107 | + const d = await queryFn(controller.signal); |
| 108 | + |
| 109 | + if (ignore) return; |
| 110 | + |
| 111 | + cache.set(queryKey, d); |
| 112 | + setData(d); |
| 113 | + setIsLoading(false); |
| 114 | + } catch (err) { |
| 115 | + if (!controller.signal.aborted) { |
| 116 | + setError((Boolean(err) && err.message) || 'Unknown error'); |
| 117 | + setIsLoading(false); |
| 118 | + } |
| 119 | + } |
| 120 | + })(); |
| 121 | + }, debounceMs); |
| 122 | + |
| 123 | + return () => { |
| 124 | + ignore = true; |
| 125 | + if (timeoutRef.current) { |
| 126 | + clearTimeout(timeoutRef.current); |
| 127 | + } |
| 128 | + if (abortControllerRef.current) { |
| 129 | + abortControllerRef.current.abort(); |
| 130 | + } |
| 131 | + }; |
| 132 | + |
| 133 | + // Don't rerender if queryFn is different, this can cause an endless render loop if |
| 134 | + // the component calling useQuery uses a closure like queryFn: () => fetchFn(someLocalVar). |
| 135 | + |
| 136 | + // This could be fixed by wrapping the closure in a useCallback in the calling component |
| 137 | + // or including a dependency array in this hook. All should work fine if all the queryFn |
| 138 | + // depends on is included in the queryKey. |
| 139 | + |
| 140 | + // eslint-disable-next-line react-hooks/exhaustive-deps |
| 141 | + }, [queryKey, cache, debounceMs]); |
| 142 | + |
| 143 | + return { data, isLoading, error }; |
| 144 | +}; |
0 commit comments