Initial offline value of a shared document

When I create a new notebook “cats”, I can initialize the content with, for example, an empty paragraph or with some kind of template and sync that document to other users. Then I can render it.

When I open a document, I need to have it already (e.g. locally stored in y-indexeddb) or download it from another client / server. Then I can render it.

What you are trying to do is something really complicated (I’m not sure you are aware of the trouble you are in). You want to be able to open a document and see some “template” content before you download it from another client. E.g., when you open a notebook “cats”, you want to be able to render the template, that doesn’t show the latest (or any!) state of the document.

The user-experience is rather questionable. I open a document and see some initial content. Then, magically, the content might appear once you have a connection.

Now that this is out of the way. You can do what you are describing to do.

// temporarily change your client id:
const myID = ydoc.clientID
ydoc.clientID = 0
// insert the initial content
ydoc.getXmlFragemnt().insert(0, new Y.XmlElement('p'))
ydoc.clientID = myID

This was a common thing to do in Yjs v11 (a few years back). It allows you to initialize the state with some initial content (e.g. an empty paragraph). However, once a client initializes state slightly differently, you will break all documents. I can’t stress how dangerous this code is. I believe there is no good reason to use that “initialization pattern” which proofed to be far too dangerous in practice. For that reason, I won’t help you when you break your documents (you might receive error messages, or simply have divergent state). I encourage you to use the idiomatic approach that I explained at the beginning.

1 Like