UNPKG

react-async-iterators

Version:

The magic of JavaScript async iterators in React ⛓️ 🧬 🔃

30 lines 1.57 kB
import { useMemo } from 'react'; import { reactAsyncIterSpecialInfoSymbol, } from '../common/ReactAsyncIterable.js'; import { useLatest } from '../common/hooks/useLatest.js'; import { asyncIterSyncMap } from '../common/asyncIterSyncMap.js'; export { useAsyncIterMemo }; const useAsyncIterMemo = (factory, deps) => { const latestDepsRef = useLatest(deps); const depsWithFormattedItersAccountedFor = latestDepsRef.current.map(dep => isReactAsyncIterable(dep) ? dep[reactAsyncIterSpecialInfoSymbol].origSource : dep); const result = useMemo(() => { const depsWithWrappedFormattedIters = latestDepsRef.current.map((dep, i) => { const specialInfo = isReactAsyncIterable(dep) ? dep[reactAsyncIterSpecialInfoSymbol] : undefined; return !specialInfo ? dep : (() => { let iterationIdx = 0; return asyncIterSyncMap(specialInfo.origSource, value => latestDepsRef.current[i][reactAsyncIterSpecialInfoSymbol].formatFn(value, iterationIdx++) // TODO: Any chance there won't be a `.formatFn` here if its possible that this might be called somehow at the moment the deps were changed completely? ); })(); }); return factory(...depsWithWrappedFormattedIters); }, depsWithFormattedItersAccountedFor); return result; }; function isReactAsyncIterable(input) { const inputAsAny = input; return !!inputAsAny?.[reactAsyncIterSpecialInfoSymbol]; } //# sourceMappingURL=index.js.map