Can't get basic encoding/decoding to work

This question is best asked in code…

  import * as Y from 'yjs'
  import { fromUint8Array, toUint8Array } from 'js-base64'
  
  const doc1 = new Y.Doc()
  const map = doc1.getMap('foo')
  map.set('bar', 'baz')

  console.log(doc1.get('foo').toJSON())

  // {bar: 'baz'}

  const update = Y.encodeStateAsUpdate(doc1)
  const base64encoded = fromUint8Array(update)
  console.log(base64encoded)

  // AQGksM/gCwAoAQNmb28DYmFyAXcDYmF6AA==

  const doc2 = new Y.Doc()
  Y.applyUpdate(doc2, toUint8Array(base64encoded))

  console.log(doc2.get('foo').toJSON())
  // undefined

Why hasn’t doc2 synced? I’d expect the final console.log output to be { bar: 'baz' } to match doc1

I figured this out immediately after posting. The solution is to create the shared object on doc2. So, you have to change…

  const doc2 = new Y.Doc()
  Y.applyUpdate(doc2, toUint8Array(base64encoded))

to…

  const doc2 = new Y.Doc()
  doc2.getMap('foo') // <--------- IMPORTANT
  Y.applyUpdate(doc2, toUint8Array(base64encoded))

and it works as expected. I’ll leave this here in case anyone else has the same issue.

1 Like