UNPKG

recoil-toolkit

Version:
41 lines 1.83 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useRecoilQuery = void 0; var react_1 = require("react"); var recoil_1 = require("recoil"); var signals_1 = require("./signals"); //todo freeze options object var useRecoilQuery = function (selector, options) { var _a = (0, recoil_1.useRecoilValueLoadable)(selector), state = _a.state, contents = _a.contents; var loading = state === 'loading'; var error = state === 'hasError' ? contents : undefined; var data = (state === 'hasValue' ? contents : undefined); var lastData = (0, react_1.useRef)(); (0, react_1.useEffect)(function () { if (data !== undefined) { lastData.current = data; } }, [data]); var refresh = (0, recoil_1.useRecoilRefresher_UNSTABLE)(selector); (0, react_1.useEffect)(function () { 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 (0, react_1.useEffect)(function () { return function () { if ((options === null || options === void 0 ? void 0 : options.cancelOnUnmount) === true) { (0, signals_1.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: loading, data: data !== undefined ? data : lastData.current, error: error, refresh: refresh, }; }; exports.useRecoilQuery = useRecoilQuery; //# sourceMappingURL=useRecoilQuery.js.map