|
| 1 | +// eslint-disable-next-line import/no-extraneous-dependencies -- transitive from fetchye-redux-provider |
| 2 | +import { useDispatch } from 'react-redux'; |
| 3 | +import { computeKey } from 'fetchye'; |
| 4 | +import { useCallback, useMemo } from 'react'; |
| 5 | +import { STREAM_DOMAIN } from './constants'; |
| 6 | +import oneFetchye from '../oneFetchye'; |
| 7 | +import { useStreamedPromise } from './hooks'; |
| 8 | +import { getLocalPromise, storeLocalPromise } from './actions'; |
| 9 | + |
| 10 | +export const useStreamedFetchye = ( |
| 11 | + key, |
| 12 | + options = {}, |
| 13 | + fetcher = undefined |
| 14 | +) => { |
| 15 | + const dispatch = useDispatch(); |
| 16 | + const { hash: promiseStoreKey } = computeKey(key, options); |
| 17 | + const serverPromise = useStreamedPromise(promiseStoreKey); |
| 18 | + |
| 19 | + const makeClientRequest = useCallback(() => { |
| 20 | + const localPromise = dispatch(getLocalPromise(STREAM_DOMAIN, promiseStoreKey)); |
| 21 | + if (localPromise) { |
| 22 | + return localPromise; |
| 23 | + } |
| 24 | + |
| 25 | + const promise = dispatch(oneFetchye(key, options, fetcher)); |
| 26 | + |
| 27 | + dispatch(storeLocalPromise( |
| 28 | + STREAM_DOMAIN, |
| 29 | + promiseStoreKey, |
| 30 | + promise |
| 31 | + )); |
| 32 | + |
| 33 | + return promise; |
| 34 | + }, [key, options, fetcher, promiseStoreKey, dispatch]); |
| 35 | + |
| 36 | + const shouldUseLocalPromise = !serverPromise; |
| 37 | + |
| 38 | + const localPromise = useMemo(() => { |
| 39 | + if (!shouldUseLocalPromise) return null; |
| 40 | + return makeClientRequest(); |
| 41 | + }, [shouldUseLocalPromise, makeClientRequest]); |
| 42 | + |
| 43 | + return localPromise || serverPromise; |
| 44 | +}; |
0 commit comments