Load document from JSON

I’m starting to get familiar with ProseMirror. The ultimate goal will be to create a WYSIWYG editor for a Wiki. But that’s in the future. For now I’m just getting my toes wet.

I’m following the basic demo as a starting point. I can store the state of the current document using JSON.stringify(view.editor.state.doc.toJSON()); but I wonder how to load that saved document again.

I tried passing it as doc when creating the state, but that doesn’t seem to work:

state: EditorState.create({
    doc: JSON.parse(document.getElementById('json').value),
    schema: schema,
    plugins: exampleSetup({schema})
})

Any tips?

1 Like

You have to deserialize it first with Node.fromJSON.

3 Likes

Great! Got it working. Thanks for the quick response.

Does this approach still stand? I’m getting a range error and wonder if this is still correct way of doing it.

Uncaught RangeError: Position 0 out of range
    at Function.resolve (index.js:949)
    at Node.resolveNoCache (index.js:1245)
    at readDOMChange (index.js:2451)
    at DOMChange.finish (index.js:2280)
    at editHandlers.input (index.js:3202)
    at HTMLDivElement.view.dom.addEventListener.view.eventHandlers.(anonymous function) (http://localhost:4000/js/app.js:37216:11)

The error comes from the https://github.com/ProseMirror/prosemirror-model/blob/80e4d95869688d73003aa155c9444c94465cc630/src/resolvedpos.js#L220 when I press any key in the editing area due to doc.content.size being NaN.

1 Like

Hope this helps you To get the current doc:

window.view.state.toJSON().doc

To set the initial value text from the json

new EditorView(editor.current, { state: EditorState.create({ doc: window.mySchema.nodeFromJSON(data.doc), plugins: exampleSetup({schema: mySchema}) }) })

2 Likes

Thanks to the info in this thread, I could create a plugin to save / retrieve doc from localStorage:

const saveRetrieveDocPlugin = new Plugin({
  state: {
    init(config, state) {
      const strContent = localStorage.getItem('spellcheck-content');
      if (strContent) {
        state.doc = state.schema.nodeFromJSON(JSON.parse(strContent));
      }
    },
    apply(tr) {
      if (tr.docChanged) {
        localStorage.setItem('spellcheck-content', JSON.stringify(tr.doc.toJSON()));
      }
    },
  },
});
5 Likes