Initialization Y.Map before observation fails

Hi, I have two questions about the initialization before observation.

I am now using Y.Map to store shared data and try to add initial values to make a default structure of our document.

For example, we used the following initialization function which is called before the observation function

export const initializeBank = () => {
  // initialize local
  setBank(produce((bank) => {
   Object.keys(bank).forEach((key, idx) => {
    delete bank[key];
   }) 
  }));
  setBankKey(0);

  // initialize yMap
  yMap.clear()
  yMap.set('bank', new Y.Map())
  yMap.set('numBankKey', 0)
}

However, when I execute the function before observation, it does not initialize data inside the yMap.

To see the problem deeper, I tried to execute the observation function after 2 seconds while the initialization function is still executed when the app loads. However, it still does not empty and initialize the yMap object.

When I print the yMap inside the initialization function, it prints the initialized object. However, It isn’t initialized when I call yMap again in the other functions, which is very weird. Is there anything I missed?

Without additional context, it’s not clear what the problem is. As written, your initializeBank function will definitely clear the yMap and set bank and numBankKey.

You may have to write up a small demo, as this is more of a debugging question than a conceptual question.

Oh, I found that the function works correctly when I trigger it with an external button, but it does not work correctly when it is executed automatically just after the page is refreshed.

It seems that the system needs some time to access and synchronize with the websocket server and the changes before the access to the websocket server are ignored.

Is there a way to know the server connection status or reflect the change before connection to the websocket server?

Yes, immediately after the page is refreshed, the Y.Doc is always empty because it has yet to sync with a provider.

Yes, you can use websocketProvider.on('status', ...) and websocketProvider.on('sync', ...) to respond to connection or sync status changes, respectively. See the y-websocket README for more info.

1 Like