YousefED / SyncedStore

SyncedStore CRDT is an easy-to-use library for building live, collaborative applications that sync automatically.
https://syncedstore.org
MIT License
1.71k stars 51 forks source link

"observe" doesn't work immediately after filling SyncedMap #50

Closed gustavotoyota closed 2 years ago

gustavotoyota commented 2 years ago

Hi, I stumbled on this problem that seems very simple, but I can't find info about the solution in the docs of either Yjs or SyncedStore.

"observe" doesn't work immediately after filling SyncedMap:

const store = new syncedStore({ obj: {} })

store.obj.array = []

getYjsValue(store.obj.array).observe(event => {
  console.log(event)
})

// Inserting into store.obj.array doesn't trigger console.log

"observe" works after sufficient delay:

const store = new syncedStore({ obj: {} })

store.obj.array = []

setTimeout(() => {
  getYjsValue(store.obj.array).observe(event => {
    console.log(event)
  })
}, 2000)

// Inserting into store.obj.array triggers console.log

There seems to be a delay after which I'm able to use observe. So I'm wondering: is there a hook in which I can initialize my observes?

Thanks

Btw, I'm using SyncedStore with Vue

gustavotoyota commented 2 years ago

Ok, I think I got it.

I was using some of those Sync Providers, and I think what's happening is that they are kinda initialized asynchronously and when they load they overwrite things in the shared object, which makes me lose the observes I've set before.

Can someone confirm that's more or less how it works?

YousefED commented 2 years ago

Hi @gustavotoyota !

What's probably happening is that the SyncProvider gets incoming data, and that incoming data replaces the old store.obj.array, so that array doesn't exist anymore. You can probably detect this by observing obj as well.

However, SyncedStore makes this easier because you don't need to use observe (which is a Yjs function) at all. If you're using Vue, you can directly use Vue's reactivity system.