Search code examples
javascriptreactjsdraftjsreact-draft-wysiwyg

Draft-js JSON to EditorState does not update


So, I used Draft-js to create blog posts. When a user creates a post, the data is converted to a string and sent to the server to be saved. I converted the draft-js EditorState like this: JSON.stringify(convertToRaw(editorState.getCurrentContent())).

Now, I want to add an edit post function. To do this, I get the string data from the server (in the exact same format as described above), and I try to create an editorState from it like this:

let data = convertFromRaw(res.data['postContent'])
setEditorState(EditorState.createWithContent(data)) 

This seems to work as when I run console.log(convertToRaw(editorState.getCurrentContent())) I can see that the server data is in the editorState. However, nothing is displayed inside of the editor. My question: How do I show the data to the user inside the editor, and make it editable? As in, the user can see the post and modify parts of it. Here is a screenshot of what I get (as you can see, the title is there but the editor is empty when it should say "Test data!"):

The body should have some text inside of it

Here is my full code:

import React, {useEffect, useState} from 'react'
import { EditorState, convertToRaw, convertFromRaw } from 'draft-js'
import { useLocation } from 'react-router-dom';
import { Editor } from 'react-draft-wysiwyg';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
import './css/CreateBlog.css'
import ApiClient from '../util/ApiClient';


// submit the blog post
const submitPage = async (data, postTitle, setPosted, setPostFailed) => {
  const content = JSON.stringify(convertToRaw(data));
  ApiClient.post("/blog/handle-blog", {"postTitle": postTitle,"postContent": content})
  .then((res) => {
    console.log(res)
    // there was no error
    if(res.status === 201) {
      setPosted("Your blog has been posted.")
      setPostFailed(false)
    } else {
      setPosted("There was an error.")
      setPostFailed(true)
    }
  })
}


// if this is an edit 
const getPostData = async (postID, setEditorState, setPostTitle) => {
  const res = await ApiClient.get(`/blog/get-blog/${postID}`)
  // set the title and data 
  setPostTitle(res.data['postTitle'])
  setEditorState(EditorState.createWithContent(convertFromRaw(res.data['postContent'])))  // set the editorState data
}

export default function CreateBlogpost() {
  const location = useLocation();
  const postID = location.state?.id;  // get the ID if there is one

  const [editorState, setEditorState] = useState(null);
  const [postTitle, setPostTitle] = useState("");
  const [posted, setPosted] = useState(""); // the error/success message 
  const [postFailed, setPostFailed] = useState(false); // has the blog successfully been posted?

  // handle the post button click
  const handleSubmit = async (e) => {
    e.preventDefault();
    // check the post contains data
    if(editorState === EditorState.createEmpty() || postTitle == "") { 
      setPosted("Please add some content to your post.")
      setPostFailed(true)
      return;
    }
    const data = editorState.getCurrentContent()
    await submitPage(data, postTitle, setPosted, setPostFailed);
  }
  
  useEffect(() => {
    // if the state has an ID, then you're editing a post
    if(postID) {
      getPostData(postID, setEditorState, setPostTitle)
    }
  }, [])

  return(
    <div className="create-blog">
      <div className="create-blog-text m-2 mb-3">
        <h1>{postID ? "Edit" : "Create"} a blog post</h1>
      </div>
      <div className="d-flex">
        <h3 className="m-2">Title: </h3>
        <input value={postTitle} type="text" id="fname" className="m-2" onChange={e=>setPostTitle(e.target.value)} />
        <p className="m-2">Please note: if you want to upload a photo, upload it to an image sharing site like imgur and then link the image.</p>
      </div>
      <div className="editor-container mb-3 ml-2 mr-2" 
      style={{ border: "1px solid black", minHeight: "6em", cursor: "text" }}
      >
        <Editor value={editorState} onEditorStateChange={setEditorState} />
      </div>
      <button className="button-3 m-2" onClick={(e) => handleSubmit(e)}>
        {postID ? "Edit" : // if there is a postID, then you are editing the post
        "Post" }
      </button>
      {/* <button className="button-3 m-2" onClick={(e) => handleSubmit(e)}>Save as draft</button> */}
      <h4 style={{ color: postFailed ? 'red' : 'green'}}>{posted}</h4>
    </div>
  )
}

Solution

  • change

    <Editor
        value={editorState}
        onEditorStateChange={setEditorState}
    />
    

    to

    <Editor
        editorState={editorState}
        onEditorStateChange={setEditorState}
    />