"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useAbortableAsync = useAbortableAsync; var _std = require("@kbn/std"); var _react = require("react"); /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ function useAbortableAsync(fn, deps, options) { const clearValueOnNext = options === null || options === void 0 ? void 0 : options.clearValueOnNext; const controllerRef = (0, _react.useRef)(new AbortController()); const [refreshId, setRefreshId] = (0, _react.useState)(0); const [error, setError] = (0, _react.useState)(); const [loading, setLoading] = (0, _react.useState)(false); const [value, setValue] = (0, _react.useState)(); (0, _react.useEffect)(() => { controllerRef.current.abort(); const controller = new AbortController(); controllerRef.current = controller; if (clearValueOnNext) { setValue(undefined); } try { const response = fn({ signal: controller.signal }); if ((0, _std.isPromise)(response)) { setLoading(true); response.then(setValue).catch(err => { setValue(undefined); setError(err); }).finally(() => setLoading(false)); } else { setError(undefined); setValue(response); setLoading(false); } } catch (err) { setValue(undefined); setError(err); setLoading(false); } return () => { controller.abort(); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, deps.concat(refreshId, clearValueOnNext)); return (0, _react.useMemo)(() => { return { error, loading, value, refresh: () => { setRefreshId(id => id + 1); } }; }, [error, value, loading]); }