Reputation: 83
I'm trying to get/load Y.Doc via WebSocket API (y-websocket library).
For this I wrote simple code like this. It connects to the server, but I can't load a document.
const id = 'my doc id';
const accessToken = 'my token';
const endpoint = `${WEBSOCKET_BASE}/document/${id}/`;
const params = accessToken ? { at: accessToken } : undefined;
let doc = new Doc();
doc.autoLoad = true;
const websocketProvider = new WebsocketProvider(endpoint, '', doc, {
connect: false,
params,
WebSocketPolyfill: WebSocket,
});
websocketProvider.on('status', ({ status }: any) => {
console.log('Status is' + status.toString());
});
websocketProvider.on('synced', () => {
channel.printLine('Synced');
console.log('is doc loaded: ' + doc.isLoaded.toString());
console.log('is doc synced ' + doc.isSynced.toString());
console.log(doc.getText());
});
websocketProvider.on('reload', (doc: Doc) => {
console.log('reaload');
});
doc.whenLoaded.then(() => {
console.log('loaded now');
});
websocketProvider.connect();
Maybe someone knows how to fix it?
Thanks!
Upvotes: 0
Views: 1036
Reputation: 81
You can connect your ydoc with websocket provider, like so:
import * as Y from "yjs";
import { WebsocketProvider } from "y-websocket";
const doc = new Y.Doc();
const wsProvider = new WebsocketProvider(
"wss://demos.yjs.dev",
"my-roomname",
doc
);
wsProvider.on("status", (event) => {
console.log(event.status); // logs "connected" or "disconnected"
});
You can add the other event listeners on wsProvider object.
I am adding a full working demo here, for you reference:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app">
<button id="button">Insert random number to array</button>
<div id="result" />
</div>
<script src="src/index.js"></script>
</body>
</html>
index.js
import * as Y from "yjs";
import { WebsocketProvider } from "y-websocket";
const doc = new Y.Doc();
const wsProvider = new WebsocketProvider(
"wss://demos.yjs.dev",
"my-roomname",
doc
);
wsProvider.on("status", (event) => {
console.log(event.status); // logs "connected" or "disconnected"
});
const yarray = doc.getArray("my-array");
const button = document.getElementById("button");
const resultDiv = document.getElementById("result");
button.addEventListener("click", () => {
const randomNumberBetweenZeroAndTen = Math.floor(Math.random() * 10);
yarray.push([randomNumberBetweenZeroAndTen]);
});
resultDiv.innerText = "Content of my-array: " + yarray.toArray();
yarray.observe(() => {
resultDiv.innerText = "Content of my-array: " + yarray.toArray();
});
The above implementation will sync your ydoc between two clients via websocket.
Upvotes: 2