"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useSubmitCode = void 0; var _react = require("react"); var _lodash = require("lodash"); var _constants = require("../../../common/constants"); var _types = require("../types"); var _format = require("../lib/format"); /* * 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. */ const DEBOUNCE_MS = 800; const useSubmitCode = http => { const currentRequestIdRef = (0, _react.useRef)(0); const [response, setResponse] = (0, _react.useState)(undefined); const [inProgress, setInProgress] = (0, _react.useState)(false); /* eslint-disable-next-line react-hooks/exhaustive-deps */ const submit = (0, _react.useCallback)((0, _lodash.debounce)(async config => { setInProgress(true); // Prevent an older request that resolves after a more recent request from clobbering it. // We store the resulting ID in this closure for comparison when the request resolves. const requestId = ++currentRequestIdRef.current; try { const result = await http.post(`${_constants.API_BASE_PATH}/execute`, { // Stringify the string, because http runs it through JSON.parse, and we want to actually // send a JSON string. body: JSON.stringify((0, _format.formatRequestPayload)(config, _types.PayloadFormat.UGLY)) }); if (currentRequestIdRef.current === requestId) { setResponse(result); setInProgress(false); } // else ignore this response... } catch (error) { if (currentRequestIdRef.current === requestId) { setResponse({ error }); setInProgress(false); } // else ignore this response... } }, DEBOUNCE_MS, { trailing: true }), [http]); return { response, inProgress, submit }; }; exports.useSubmitCode = useSubmitCode;