monaco-languageclient icon indicating copy to clipboard operation
monaco-languageclient copied to clipboard

[MonacoEditorReactComp] - Correct approach to store code in state

Open metehansenol opened this issue 1 year ago • 1 comments

Any idea how to store editor text in app state? Because when state changed onTextChanged event is being triggered twice because of having code also in userConfig and lost cursor position in editor. Examples and readme doesn't show usage with react state.

const [code, setCode] = useState('');

const onTextChanged = (text: string, isDirty: boolean) => {
  setCode(text);
};

<MonacoEditorReactComp
  userConfig={{
     wrapperConfig: {
      editorAppConfig: {
        ...
        code,
        ...
      },
    },
  }}
  onTextChanged={onTextChanged}
/>

metehansenol avatar May 13 '24 19:05 metehansenol

I don't think Monaco should be used as a "controlled input"; I don't think it's designed to be used that way. Instead, you can use onLoad to store a reference to the editor itself in your component's state, and then call getValue() to get the current value whenever you need it:

const [editor, setEditor] = useState();

// example of getting the current value from the editor
const onClick = () => alert(editor?.getValue());

<MonacoEditorReactComp
  userConfig={{
     wrapperConfig: {
      editorAppConfig: {
        ...
      },
    },
  }}
  onLoad={(wrapper) => setEditor(wrapper.getEditor())}
/>

vrama628 avatar Jun 22 '24 17:06 vrama628

@vrama628 provided the answer. Thank you. I will close this issue.

kaisalmen avatar Aug 08 '24 20:08 kaisalmen