Skip to content
This repository has been archived by the owner on Mar 29, 2024. It is now read-only.

Persisting Editor Data

Brijesh Bittu edited this page Nov 4, 2016 · 4 revisions

Saving the 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.

Best Practice

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 -

Using medium-draft's utility function

const blockData = JSON.parse(previouslySavedDataFromServer());
this.setState({
  editorState: createEditorState(blockData),
});

Using Draft's functions

const blockData = JSON.parse(previouslySavedDataFromServer());
this.setState({
  editorState: EditorState.push(this.state.editorState, convertFromRaw(blockData))
});