0

So I am using the DraftJS package with React along with the mentions plugin. When a post is created, I store the raw JS in my PostreSQL JSONField:

convertToRaw(postEditorState.getCurrentContent())

When I edit the post, I set the editor state as follows:

let newEditorState = EditorState.createWithContent(convertFromRaw(post.richtext_content));
setEditorState(newEditorState);

The text gets set correctly, but none of the mentions are highlighted AND I can't add new mentions. Does anyone know how to fix this?

I am using the mention plugin: https://www.draft-js-plugins.com/plugin/mention

1 Answers1

0

to save data

 function saveContent() {
    const content = editorState.getCurrentContent();
    const rawObject = convertToRaw(content);
    const draftRaw = JSON.stringify(rawObject); //<- save this to database
 
}

and retrieval:

   setEditorState(()=> EditorState.push(
          editorState,
          convertFromRaw(JSON.parse(draftRaw)),
          "remove-range"
        ););

it should preserve your data as saved.

the example provided (which works ok) is for inserting a new block with mention, saving the entityMap as well. mentionData is jus a simple object {id:.., name:.., link:... , avatar:...}

One more thing: initialize only once: in other words do not recreate the state.

const [editorState, setEditorState] = useState(() => EditorState.createEmpty() );

und then populate something like:

 useEffect(() => {
   
    try {

      if (theDraftRaw) {
        let mtyState = EditorState.push(
          editorState,
          convertFromRaw(JSON.parse(theDraftRaw)),
          "remove-range"
        );
         setEditorState(mtyState);
      } else editorClear();

    } catch (e) {
      
      console.log(e);
      // or some fallback to other field  like text 
    
    }
  }, [theDraftRaw]);
  const editorClear = () => {

    if (!editorState.getCurrentContent().hasText()) return;

    let _editorState = EditorState.push(
      editorState,
      ContentState.createFromText("")
    );
    setEditorState(_editorState);
  };
Vlad
  • 21
  • 1
  • 2