UNPKG

recoil-toolkit

Version:
37 lines 1.57 kB
import { useEffect, useRef } from 'react'; import { useRecoilRefresher_UNSTABLE, useRecoilValueLoadable } from 'recoil'; import { doCancelSignal } from './signals'; //todo freeze options object export const useRecoilQuery = (selector, options) => { const { state, contents } = useRecoilValueLoadable(selector); const loading = state === 'loading'; const error = state === 'hasError' ? contents : undefined; const data = (state === 'hasValue' ? contents : undefined); const lastData = useRef(); useEffect(() => { if (data !== undefined) { lastData.current = data; } }, [data]); const refresh = useRecoilRefresher_UNSTABLE(selector); useEffect(() => { if ((options === null || options === void 0 ? void 0 : options.refreshOnMount) === 'always' || ((options === null || options === void 0 ? void 0 : options.refreshOnMount) === 'error' && error)) { !loading && refresh(); } }, []); //eslint-disable-line useEffect(() => () => { if ((options === null || options === void 0 ? void 0 : options.cancelOnUnmount) === true) { doCancelSignal(selector.key); } if (typeof (options === null || options === void 0 ? void 0 : options.cancelOnUnmount) === 'function') { options === null || options === void 0 ? void 0 : options.cancelOnUnmount(); } }, []); return { loading, data: data !== undefined ? data : lastData.current, error, refresh, }; }; //# sourceMappingURL=useRecoilQuery.js.map