How to decode the snapshot of yjs

I am tried like this to save the history of yjs:

let history: Uint8Array[] = [];
var ydoc:Y.Doc;
export function saveHistory(){
    const snapshot = Y.encodeStateAsUpdate(ydoc);
    history.push(snapshot);
    const text = Y.decodeSnapshot(snapshot);
    console.log(text);
}

the decode shows error:

Error: Integer out of Range
    at create2 (error.js:12:28)
    at decoding.js:37:38

Am I doing the decode the right way? what should I to do decode the yjs binary to plain text?

First you should clarify if you want an update or a snapshot.

  • Y.encodeStateAsUpdate returns an update (representing the entire history of the Doc), not a snapshot (see Note 2 below).
  • Y.snapshot returns a snapshot.

Demo: View in CodeSandbox

A few notes:

  1. A Doc already has the full history. So when you save the updates (or persist the Doc), the full history is saved.
  2. A snapshot, in YJS terms, contains just a set of clocks, ids, and deletes that allows you to identify the state at a specific point in time. It does not contain any of the actual content. So you need to combine it with the original Doc to restore specific states. This will be obvious when you use the createDocFromSnapshot, which takes the original Doc as an argument.
  3. Y.createDocFromSnapshot creates an entirely new Doc and does not change the state of the old Doc. To revert to an update (in the sense of git revert), you need to calculate the delta and apply it manually to the original Doc.
2 Likes

Hi Raine, seems like the codsanbox link is empty. If possible can you update the link?

@websiddu Try it now!