So i am recently working on this collaborative text editor using React, and socket.io.
My app.js looks somewhat like this :
const [content, updateContent] = useState('');
socket.on("update", (data)=>{
if(access === true){
currContent = data
updateContent(data)
}
})
const contentBlock = htmlToDraft(content);
const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
const editorState = EditorState.createWithContent(contentState);
class ControlledEditor extends Component {
constructor(props) {
super(props);
this.state = {
editorState,
};
}
onEditorStateChange: Function = (editorState) => {
this.setState({
editorState,
});
if(access===true && user==="Admin"){
currContent = draftToHtml(convertToRaw(editorState.getCurrentContent()))
socket.emit("message",[currContent,id])}
};
render() {
const { editorState } = this.state;
if(access === true && user==="Admin"){
return (
<Editor
editorState={editorState}
wrapperClassName="demo-wrapper"
editorClassName="demo-editor"
onEditorStateChange={this.onEditorStateChange}
/>
)})
}
}
}
What's happening : Whenever any person in the room types something it emits a socket event which is then listened by every client in the room and everyone changes the value of useState content, which forces a re-render on every client's editor who received the content, due to this its not practically possible to write at the same time as the editor changes its value to something new while you are typing.
What should happen : All the clients in the room should get the data and get it updated on their editors but all should be able to write at the same time just like what happens on google docs.
I am currently using react-draft-wysiwyg for this, i know their are plenty of other text editors available as well and i am totally comfortable in changing the editor if any of then help me solve this issue.
You can try this on : https://kalam-editor.herokuapp.com/opendocument just enter the docid : 1234 and password : 1234 as well. (If it shows docid dosn't exist just click on the open doc button 2-3 times)