How to update the code in editor with react(like formater)?

I’ve a code formatter function, and I just wanna add a button in the page, when customer click the button, the code in the editor would be updated.

The demo run as:

  useEffect(() => {
    if (file) {
      const cur = editorStates.current[file]
      const originCode = cur.doc.toString()
      if (format) {
        console.log('original code: ' + originCode)
        const formattedCode = pretty(originCode)
        console.log('formated code: ' + formattedCode.code)
  }, [format, file])

I was wondering how to put formattedCode back to the editor?

Either dispatch({changes: {from: 0, to: cur.doc.length, insert: formattedCode}}) or, if you want to preserve stuff like collapsed code and other position-dependent state, compute a diff between the unformatted and formatted code and apply only the minimal changes.

1 Like