TypeFox / monaco-languageclient

Repo hosts npm packages for monaco-languageclient, vscode-ws-jsonrpc, monaco-editor-wrapper, @typefox/monaco-editor-react and monaco-languageclient-examples
https://www.npmjs.com/package/monaco-languageclient
MIT License
992 stars 171 forks source link

[MonacoEditorReactComp] - Correct approach to store code in state #659

Open metehansenol opened 1 month ago

metehansenol commented 1 month ago

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}
/>
vrama628 commented 1 week ago

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())}
/>