Skip to content

Commit

Permalink
fix stale onChange issue
Browse files Browse the repository at this point in the history
  • Loading branch information
Dosant committed Feb 6, 2024
1 parent d159d73 commit 887d58f
Showing 1 changed file with 20 additions and 1 deletion.
21 changes: 20 additions & 1 deletion packages/shared-ux/code_editor/impl/code_editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ export interface CodeEditorProps {
export const CodeEditor: React.FC<CodeEditorProps> = ({
languageId,
value,
onChange,
onChange: _onChange,
width,
height,
options,
Expand Down Expand Up @@ -208,6 +208,8 @@ export const CodeEditor: React.FC<CodeEditorProps> = ({
refreshMode: 'debounce',
});

const onChange = useBug175684OnChange(_onChange);

const startEditing = useCallback(() => {
setIsHintActive(false);
_editor.current?.focus();
Expand Down Expand Up @@ -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<CodeEditorProps['onChange']>(onChange);
useEffect(() => {
onChangePropRef.current = onChange;
}, [onChange]);
const onChangeWrapper = useCallback<NonNullable<CodeEditorProps['onChange']>>((_value, event) => {
if (onChangePropRef.current) {
onChangePropRef.current(_value, event);
}
}, []);

return onChangeWrapper;
};

0 comments on commit 887d58f

Please sign in to comment.