UNPKG

one

Version:

One is a React framework for web, iOS, and Android apps.

58 lines (55 loc) • 2.03 kB
import { useCallback, useLayoutEffect, useRef, useState } from "react"; import { createLatestComputation } from "./createLatestComputation.native.js"; function useBackgroundComputation(definition, input) { var _submitted_current, _owner_current; var [state, setState] = useState({ phase: "idle", revision: 0 }); var owner = useRef(null); var submitted = useRef(null); var active = input !== null; useLayoutEffect(function() { if (!active) return; var computation = createLatestComputation(definition, function(changed) { setState(changed.phase === "ready" ? { phase: "ready", revision: changed.result.revision } : changed); }); owner.current = computation; return function() { owner.current = null; submitted.current = null; computation.dispose(); }; }, [active, definition]); useLayoutEffect(function() { var _owner_current2; if (input === null) return; submitted.current = { input, factory: definition }; (_owner_current2 = owner.current) === null || _owner_current2 === void 0 ? void 0 : _owner_current2.update(input); }, [ active, definition, input ]); var getCurrent = useCallback(function() { var _ref; var _owner_current2; return (_ref = (_owner_current2 = owner.current) === null || _owner_current2 === void 0 ? void 0 : _owner_current2.getCurrent()) !== null && _ref !== void 0 ? _ref : null; }, []); var matches = active && ((_submitted_current = submitted.current) === null || _submitted_current === void 0 ? void 0 : _submitted_current.input) === input && submitted.current.factory === definition; if (matches && state.phase === "failed") throw state.error; var current = (_owner_current = owner.current) === null || _owner_current === void 0 ? void 0 : _owner_current.getCurrent(); var result = matches && state.phase === "ready" && current && state.revision === current.revision ? current : null; return { result, getCurrent }; } export { useBackgroundComputation }; //# sourceMappingURL=useBackgroundComputation.native.js.map