UNPKG

mutoid

Version:

Reactive library for data fetching, caching, state management

38 lines (37 loc) 1.54 kB
/* istanbul ignore file */ import { useCallback, useState, useRef, useEffect } from 'react'; import { map, takeUntil } from 'rxjs/operators'; import * as MRE from '../http/Resource'; import { useSubscriptionRef } from './useSubscriptionRef'; /** * @deprecated */ export function useResourceFetcher(fetch, options) { const [value, setValue] = useState(options?.iniState || MRE.init); const [subscriptionRef, subscriptionUnsubscribe] = useSubscriptionRef(); const fetchRef = useRef(fetch); const notifierTakeUntilRef = useRef(options?.notifierTakeUntil); const mapAcknowledgedRef = useRef(options?.mapAcknowledged); useEffect(() => { fetchRef.current = fetch; notifierTakeUntilRef.current = options?.notifierTakeUntil; mapAcknowledgedRef.current = options?.mapAcknowledged; }, [fetch, options]); return [ value, useCallback((...p) => { subscriptionUnsubscribe(); const resource$ = fetchRef.current(...p); const resourceTaken$ = notifierTakeUntilRef.current ? resource$.pipe(takeUntil(notifierTakeUntilRef.current)) : resource$; subscriptionRef.current = resourceTaken$ .pipe(map(s => { return mapAcknowledgedRef.current && (s._tag === 'done' || s._tag === 'fail') ? mapAcknowledgedRef.current(s) : s; })) .subscribe(setValue); }, [subscriptionRef, subscriptionUnsubscribe]), ]; }