Ace editor with ReactJS - undo functionality

Viewed 1293

I am using Ace editor with React (https://github.com/securingsincity/react-ace, version: 8.0.0)

I have managed to add an undo button, but undoing on a new editor instance is erasing the whole document.

My code so far :

class AceEditor extends React.Component {

  constructor(props, context) {
    super(props, context);

    this.editor = React.createRef();
  }

  componentDidMount() {
    this.setState({
      code: "Test text"
    })
  }

  render() {
    const {code} = this.state;

    return (
      <div>
        <Button onClick={() => {
          this.editor.current.editor.undo()
        }}/>

        <AceEditor
          ref={this.editor}
          value={code}
          // more props
          onLoad={editor => {
            const session = editor.getSession();
            const undoManager = session.getUndoManager();
            undoManager.reset();
            session.setUndoManager(undoManager);
          }}
        />
      </div>
    );
  }
}

What am I missing, any workarounds?

1 Answers

this happens because onload is called before value={code} is processed, a hacky workaround is:

onLoad={editor => {
    editor.once("change", function() {
        editor.session.getUndoManager().reset();
    });
}}

https://codesandbox.io/s/sharp-kalam-yen89

Related