-
Notifications
You must be signed in to change notification settings - Fork 244
Persisting Editor Data
After researching various use cases/editors based on draft-js, I have noticed that developers are using HTML/Markdown as an intermediate stage. They are converting draft
's contentState
to html or markdown using some libraries for ex like draft-js-export-html, then saving that in DB. And when they want to prefill the editor again, they convert back the HTML to contentState
.
This may seem like an obvious choice but it is not.
This process may result in loss of information from some blocks/entities or custom data that you may have implemented in your blocks.
The best way to save the editor data is to directly save the JSON that is obtained as a result of -
var editorData = convertToRaw(this.state.editorState.getCurrentContent());
Here editorData
will be a Javascript object that has all the information of your current editor data. You can send this value to your server and save it in the DB.
If the DB that you are using supports any kind of JSON/Binary JSON, you can save the above information directly in that column. But if you don't have that option, you can instead convert the JSON to its string representation either on server or on client and then save that to a normal TEXT/VARCHAR column.
And when you have to refill the editor when the user reloads it, you can fetch the json that you saved previously and then use convertFromRaw
to convert it to ContentState
and then set it as your editorState
-
const blockData = JSON.parse(previouslySavedDataFromServer());
this.setState({
editorState: createEditorState(blockData),
});
const blockData = JSON.parse(previouslySavedDataFromServer());
this.setState({
editorState: EditorState.push(this.state.editorState, convertFromRaw(blockData))
});