'Removing All Entities Wipes Out Text Content

I've written a function that removes all entities from the Draft JS rich text editor.

I run it once when the component loads, and then every time the component updates.

It works well, removing all the entities from the pre-populated text at first, however, as soon as I start changing the text content in the rich text editor, all other content gets removed, and only the last character I've pressed on my keyboard remains in the rich text editor.

Code:

export default class EditorConvertToHTML extends Component {
    constructor(props) {
      super(props)
      const contentBlocks = htmlToDraft(props.content)
      const contentState = ContentState.createFromBlockArray(contentBlocks)
      const editorState = EditorState.createWithContent(contentState)
  
      this.state = {
        editorState: this.removeEntities(editorState)
      }
    }

    removeEntities(editorState){
        let contentState = editorState.getCurrentContent()
        contentState.getBlockMap().forEach(block => {
          const blockKey = block.getKey();
          const blockText = block.getText();
          // Create a selection for entire length of text in the block
          const selection = SelectionState.createEmpty(blockKey);
          const updatedSelection = selection.merge({
            //anchorOffset is the start of the block
            anchorOffset: 0,
            // focustOffset is the end
            focusOffset: blockText.length
          })
          contentState = Modifier.applyEntity(contentState, updatedSelection, null);
        });
    
        const newEditorState = EditorState.push(
          editorState,
          contentState,
          'apply-entity'
        );
    
        return newEditorState
      }

      onEditorStateChange = (editorState) => {
        this.setState({
          editorState: this.removeForbiddenStyles(editorState)
        });
      };

      render() {
        const { editorState } = this.state
        return (
            <Editor
              editorState={editorState}
              onEditorStateChange={this.onEditorStateChange}
            />
        )
    }
}

Why does the existing content get wiped out as soon as I start editing the text in the rich text editor?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source