reactjsreact-draft-wysiwyg

State retrieved from react-draft-wysiwyg is always one step behind


I'm trying to implement something like a Mobile Preview section where after the user do their things in the editor, the changes that they've made will be shown in the Preview section concurrently.

The issue that I'm facing now is the method that I'm using in Bulletin.js to retrieve the html content from the editor seems to be 1 step behind (as in I need to do some actions like clicking anywhere or to retrieve the last action made in the editor).

I want to make it so that the change is instant and not one step behind so that when user do things like changing font colour etc, it will be reflected to the preview section instantly.

Bulletin.js

const getContent = (htmlContentProp) => {
    setHtmlContent(draftToHtml(htmlContentProp));
};

<RichTextEditor getContent={getContent} htmlContent={htmlContent} />

RichTextEditor.js

const handleEditorChange = (state) => {
    setEditorState(state);
    getContent(convertToRaw(editorState.getCurrentContent()));
};

Edit unruffled-ptolemy-8m2cr


Solution

  • Issue is here:

    const handleEditorChange = (state) => {
        setEditorState(state); // this is asynchronous
        // so this will most likely be old value
        getContent(convertToRaw(editorState.getCurrentContent()));
    };
    

    You have 2 easy options to work around this

    const handleEditorChange = (state) => {
        getContent(convertToRaw(state.getCurrentContent()));
    };
    
    const handleEditorChange = (state) => {
        setEditorState(state); // this is asynchronous
    };
    
    useEffect(() => { 
        getContent(convertToRaw(editorState.getCurrentContent()));
    }, [editorState]); // this effect will trigger once the editorState actually changes value