Hello,
I have a codemirror instance bound to a ydoc. My problem is that when I change the content of the ydoc by running
ydoc.current.transact(() => {
ytext.current.insert(0, "hello world");
});
the text in codemirror is not getting updated. What am I doing wrong here (full source code below)? Thanks a lot for your help.
import CodeMirror from "@uiw/react-codemirror";
import { StrictMode, useEffect, useState, useRef } from "react";
//collaborative editing
import * as Y from "yjs";
import { yCollab } from "y-codemirror.next";
import { WebrtcProvider } from "y-webrtc";
function Editor() {
const ydoc = useRef(new Y.Doc());
const ytext = useRef(ydoc.current.getText("codemirror"));
const [provider, setProvider] = useState();
const providerInitialized = useRef(false);
//const undoManager = useRef(new Y.UndoManager(ytext.current));
useEffect(() => {
if (providerInitialized.current) return;
console.log("running use effect");
const __provider = new WebrtcProvider("statscamp-demo", ydoc.current, {
signaling: [
"wss://signaling.yjs.dev",
"wss://y-webrtc-signaling-eu.herokuapp.com",
"wss://y-webrtc-signaling-us.herokuapp.com"
]
});
__provider.awareness.setLocalStateField("user", {
name: "Anonymous " + Math.floor(Math.random() * 100),
color: "#30bced",
colorLight: "#30bced33"
});
setProvider(__provider);
ydoc.current.transact(() => {
ytext.current.insert(0, "hello world");
});
console.log(ytext.current.toString());
providerInitialized.current = true;
return () => {
if (provider) {
provider.disconnect(); //We destroy doc we created and disconnect
provider.destroy();
ydoc.current.destroy(); //the provider to stop propagting changes if user leaves editor
}
};
}, []);
if (!provider || !providerInitialized.current) return null;
return (
<>
<CodeMirror extensions={[yCollab(ytext.current, provider.awareness)]} />
</>
);
}
export default function App() {
return (
<StrictMode>
<div className="App">
<Editor />
</div>
</StrictMode>
);
}