How can I differentiate a Yjs observer call between sender and receiver?

So I’ve structure like Ymap.observe(changeObserver) and inside the changeObserver I’m dispatching a redux call to update the redux.
This is mainly intended to update the redux of all the clients connected to the ydoc.

But this changeObserver will also get triggered when I make a change. So in that case is there any way to identify if the change is done by me or not?
I did try the Transaction.local but it did not work.

Hi, welcome.

You can check the transaction origin. It will point to the Doc’s clientId when the transaction originates from the current client and it will point to the provider when it comes from other clients.

I’ve been using the following condition but I can’t confirm that it works in all cases.

map.observe(e => {
  // bail if the transaction originates on this client
  if (e.transaction.origin === e.target.doc.clientId) return
})

Thanks for the reply!
A follow up question though, won’t the e.transaction.origin an object?

Ah, I knew I was missing something. This works because I explicitly set the origin to doc.clientID:

doc.transact(() => {
  ...
}, doc.clientID)

When a transaction originates on a remote client, the origin is always set to the provider instance, regardless of what was passed to transact on that client.

1 Like

So I tried this,

yDoc.transact(() => {
    notesMap.set(_id, JSON.stringify(noteToUpdate));
}, noteToUpdate.lastUpdatedBy.toString());

This is the approach I took but it did not work.
I’m updating the ydoc from server side in node js and not client side.

Server-side origins don’t make it to the client-side unfortunately. When the transaction originates from another client, the origin is set to the WebsocketProvider instance itself.

If lastUpdatedBy is set in the Y.Map itself, you should be able to read it from there on the client-side though.

1 Like