Why does this simple update fail?

I’m trying to play around with yjs and I’m trying to sync two documents without the use of a state vector. I can’t figure out what’s wrong with the following code:

const Y = require('yjs');

// Generate update
const doc1 = new Y.Doc();
doc1.getArray('array').push([1, 2, 3]);
const update1 = Y.encodeStateAsUpdateV2(doc1);

// Apply updates to the new document
const doc2 = new Y.Doc();
Y.applyUpdateV2(doc2, update1);

// Print the merged document
console.log(JSON.stringify(doc2)); // got: {}, expected {"array":[1,2,3]}

Any ideas on what I might be doing wrong?

In general, you can’t assume that you can stringify everything. JSON.stringify(doc2) is not something that Yjs supports. Modern JavaScript builds on types, implemented using classes, that have custom behavior depending on the methods you call. JSON stringify doesn’t know about the internal Yjs logic.

doc2.getArray('array').toJSON() will give you the expected result.

ah, so it does. what confused me is that if you look at the help for


it says Do not use this method and rather call toJSON directly on the shared types which I interpreted as calling JSON.stringify(doc), but clearly it was what you meant