|
| 1 | +import React, { useRef, useMemo } from 'react' |
| 2 | +import useSWR, { unstable_serialize } from 'swr' |
| 3 | +import { |
| 4 | + createCacheHelper, |
| 5 | + SWRHook, |
| 6 | + Middleware, |
| 7 | + withMiddleware, |
| 8 | + isUndefined, |
| 9 | + useIsomorphicLayoutEffect, |
| 10 | + mergeObjects, |
| 11 | + MutatorOptions, |
| 12 | + MutatorCallback, |
| 13 | + Arguments, |
| 14 | + RevalidatorOptions, |
| 15 | + SWRGlobalState, |
| 16 | + getTimestamp, |
| 17 | + GlobalState, |
| 18 | + BareFetcher, |
| 19 | + defaultConfig |
| 20 | +} from 'swr/_internal' |
| 21 | + |
| 22 | +import type { |
| 23 | + SWRItemProps, |
| 24 | + SWRAggregatorConfiguration, |
| 25 | + SWRAggregator, |
| 26 | + SWRCollection |
| 27 | +} from './types' |
| 28 | + |
| 29 | +const Fallback = ({ originKey, fetcher }: SWRItemProps) => { |
| 30 | + useSWR(originKey, fetcher) |
| 31 | + return null |
| 32 | +} |
| 33 | + |
| 34 | +export const aggregator = (<Data, Error, Key extends Arguments = Arguments>( |
| 35 | + useSWRNext: SWRHook |
| 36 | + ) => |
| 37 | + ( |
| 38 | + _keys: Key[], |
| 39 | + fetcher: BareFetcher<Data>, |
| 40 | + config: typeof defaultConfig & SWRAggregatorConfiguration<Data, Error, Key> |
| 41 | + ) => { |
| 42 | + if (!Array.isArray(_keys)) throw new Error('not array') |
| 43 | + const { |
| 44 | + cache, |
| 45 | + compare, |
| 46 | + mutate: _internalMutate, |
| 47 | + SWRItem = Fallback |
| 48 | + } = config |
| 49 | + const fetcherRef = useRef(fetcher) |
| 50 | + const configRef = useRef(config) |
| 51 | + const swrkeys = unstable_serialize(_keys) |
| 52 | + // eslint-disable-next-line react-hooks/exhaustive-deps |
| 53 | + const keys = useMemo(() => _keys.map(v => unstable_serialize(v)), [swrkeys]) |
| 54 | + const cacheHelpers = useMemo( |
| 55 | + () => |
| 56 | + keys.map(key => { |
| 57 | + const [get] = createCacheHelper<Data>(cache, key) |
| 58 | + return { |
| 59 | + get |
| 60 | + } |
| 61 | + }), |
| 62 | + [keys, cache] |
| 63 | + ) |
| 64 | + |
| 65 | + const currentFetcher = fetcherRef.current |
| 66 | + |
| 67 | + const fetch = async (revalidateOpts?: RevalidatorOptions): Promise<any> => { |
| 68 | + const revalidate = async (index: number) => { |
| 69 | + let newData: Data |
| 70 | + let startAt: number |
| 71 | + const opts = revalidateOpts || {} |
| 72 | + const key = keys[index] |
| 73 | + const _key = _keys[index] |
| 74 | + const { get } = cacheHelpers[index] |
| 75 | + const [_, MUTATION, FETCH] = SWRGlobalState.get(cache) as GlobalState |
| 76 | + // If there is no ongoing concurrent request, or `dedupe` is not set, a |
| 77 | + // new request should be initiated. |
| 78 | + const shouldStartNewRequest = !FETCH[key] || !opts.dedupe |
| 79 | + |
| 80 | + const cleanupState = () => { |
| 81 | + // Check if it's still the same request before deleting. |
| 82 | + const requestInfo = FETCH[key] |
| 83 | + if (requestInfo && requestInfo[1] === startAt) { |
| 84 | + delete FETCH[key] |
| 85 | + } |
| 86 | + } |
| 87 | + try { |
| 88 | + if (shouldStartNewRequest) { |
| 89 | + FETCH[key] = [currentFetcher(_key), getTimestamp()] |
| 90 | + } |
| 91 | + ;[newData, startAt] = FETCH[key] |
| 92 | + newData = await newData |
| 93 | + |
| 94 | + if (shouldStartNewRequest) { |
| 95 | + setTimeout(cleanupState, config.dedupingInterval) |
| 96 | + } |
| 97 | + const mutationInfo = MUTATION[key] |
| 98 | + if ( |
| 99 | + !isUndefined(mutationInfo) && |
| 100 | + // case 1 |
| 101 | + (startAt <= mutationInfo[0] || |
| 102 | + // case 2 |
| 103 | + startAt <= mutationInfo[1] || |
| 104 | + // case 3 |
| 105 | + mutationInfo[1] === 0) |
| 106 | + ) { |
| 107 | + return mergeObjects({}, { data: get().data, error: get().error }) |
| 108 | + } |
| 109 | + if (!compare(newData, get().data)) { |
| 110 | + await _internalMutate(_key, newData, false) |
| 111 | + } |
| 112 | + // eslint-disable-next-line no-empty |
| 113 | + } catch { |
| 114 | + cleanupState() |
| 115 | + } |
| 116 | + return mergeObjects({}, { data: get().data, error: get().error }) |
| 117 | + } |
| 118 | + return Promise.all(keys.map((___, i) => revalidate(i))) |
| 119 | + } |
| 120 | + const swr = useSWRNext(_keys, () => fetch({ dedupe: true }), config) |
| 121 | + const itemRender = (key: any, index: number) => ( |
| 122 | + <SWRItem |
| 123 | + key={key} |
| 124 | + originKey={_keys[index]} |
| 125 | + collection={swr} |
| 126 | + fetcher={async () => { |
| 127 | + const data = await currentFetcher(_keys[index]) |
| 128 | + swr.mutate() |
| 129 | + return data |
| 130 | + }} |
| 131 | + /> |
| 132 | + ) |
| 133 | + |
| 134 | + useIsomorphicLayoutEffect(() => { |
| 135 | + fetcherRef.current = fetcher |
| 136 | + configRef.current = config |
| 137 | + }) |
| 138 | + |
| 139 | + return { |
| 140 | + result: keys.map(itemRender), |
| 141 | + mutate: ( |
| 142 | + data: Data[] | Promise<Data[]> | MutatorCallback<Data[]> = () => |
| 143 | + fetch({ dedupe: false }), |
| 144 | + opt: boolean | MutatorOptions<Data[]> = false |
| 145 | + ) => swr.mutate(data, opt), |
| 146 | + get data() { |
| 147 | + return swr.data?.map((v: any, i: number) => |
| 148 | + mergeObjects(v, { |
| 149 | + key: keys[i], |
| 150 | + originKey: _keys[i] |
| 151 | + }) |
| 152 | + ) |
| 153 | + }, |
| 154 | + get isLoading() { |
| 155 | + return swr.isLoading |
| 156 | + }, |
| 157 | + get isValidating() { |
| 158 | + return swr.isValidating |
| 159 | + } |
| 160 | + } |
| 161 | + }) as unknown as Middleware |
| 162 | + |
| 163 | +export default withMiddleware(useSWR, aggregator) as unknown as SWRAggregator |
| 164 | + |
| 165 | +export { |
| 166 | + SWRItemProps, |
| 167 | + SWRAggregatorConfiguration, |
| 168 | + SWRAggregator, |
| 169 | + SWRCollection |
| 170 | +} |
0 commit comments