Save Draft.js content using convertFromRaw and convertToRaw

To store the content created with Draft.js, we can use convertToRaw and convertFromRaw functions. Here is an example on how to use these functions in React:

jsx
import React, { useEffect, useRef, useState }         from 'react';
import { EditorState, convertFromRaw, convertToRaw }  from 'draft-js';
import Editor                                         from 'draft-js-plugins-editor';
import createMarkdownShortcutsPlugin                  from 'draft-js-md-keyboard-plugin';

const MdEditor = () => {
    
    const [editorState, setEditorState] = useState(EditorState.createEmpty());
    const mdPlugin                      = [createMarkdownShortcutsPlugin()];
    
    useEffect( () => {
    
        loadContent();
    
    }, []);
    
    useEffect( () => {
        
        saveContent();
    
    }, [editorState]);
    
    const loadContent = () => {
    
        // Getting content from database
        let dataBaseContent = getContentFromDataBase();
    
        // Getting content back
        let content = convertFromRaw(JSON.parse(dataBaseContent));
        
        // Setting the state
        setEditorState(EditorState.createWithContent(content));
        
    }
    
    const saveContent = () => {
        
        // This content can be stored on a database
        let content = JSON.stringify(convertToRaw(editorState.getCurrentContent()));
        
    }
    
    return(
        
        <Editor
            editorState = { editorState }
            onChange    = { (editorState) => setEditorState(editorState) }
            placeholder = 'Type here or press ⌘ + V to paste your content'
            plugins     = { mdPlugin }
        />
    )
    
}

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.