diff --git a/packages/shared-ux/code_editor/impl/code_editor.tsx b/packages/shared-ux/code_editor/impl/code_editor.tsx index b41906d5ed456..a662356a216ee 100644 --- a/packages/shared-ux/code_editor/impl/code_editor.tsx +++ b/packages/shared-ux/code_editor/impl/code_editor.tsx @@ -145,7 +145,7 @@ export interface CodeEditorProps { export const CodeEditor: React.FC = ({ languageId, value, - onChange, + onChange: _onChange, width, height, options, @@ -208,6 +208,8 @@ export const CodeEditor: React.FC = ({ refreshMode: 'debounce', }); + const onChange = useBug175684OnChange(_onChange); + const startEditing = useCallback(() => { setIsHintActive(false); _editor.current?.focus(); @@ -640,3 +642,20 @@ const useCopy = ({ isCopyable, value }: { isCopyable: boolean; value: string }) return { showCopyButton, CopyButton }; }; + +// https://github.com/elastic/kibana/issues/175684 +// 'react-monaco-editor' has a bug that it always calls the initial onChange callback, so the closure might become stale +// we work this around by calling the latest onChange from props +const useBug175684OnChange = (onChange: CodeEditorProps['onChange']) => { + const onChangePropRef = useRef(onChange); + useEffect(() => { + onChangePropRef.current = onChange; + }, [onChange]); + const onChangeWrapper = useCallback>((_value, event) => { + if (onChangePropRef.current) { + onChangePropRef.current(_value, event); + } + }, []); + + return onChangeWrapper; +};