Skip to content

Instantly share code, notes, and snippets.

@GaetanoPiazzolla
Last active May 17, 2021 14:47
Show Gist options
  • Save GaetanoPiazzolla/5b2be57640cb47c0ef0c394ef1f8fe1e to your computer and use it in GitHub Desktop.
Save GaetanoPiazzolla/5b2be57640cb47c0ef0c394ef1f8fe1e to your computer and use it in GitHub Desktop.
Central part of Client of DirectCode
import React from "react";
import socketIOClient from "socket.io-client";
import {generateUniqueID} from "web-vitals/dist/lib/generateUniqueID";
import debounce from 'lodash.debounce';
import throttle from 'lodash.throttle';
class App extends React.Component {
// .... initialization code...
componentDidMount() {
this.http.get(ENDPOINT + 'latest-code').then(data => {
if (data?.data?.code) {
this.setState({code: data.data.code})
this.setState({lockStatus: this.LOCK_ACQUIRED})
}
})
this.socket = socketIOClient(ENDPOINT);
this.uuid = generateUniqueID();
this.socket.on("update-code", data => {
if (this.uuid !== data.uuid) {
this.setState({code: data.code});
this.setState({lockStatus: this.LOCK_FAILED})
}
});
this.socket.on("code-locked", data => {
if (this.uuid !== data.uuid)
this.setState({lockStatus: this.LOCK_FAILED})
});
this.socket.on("code-unlocked", data => {
if (this.uuid !== data.uuid)
this.setState({lockStatus: this.LOCK_ACQUIRED})
})
}
changeEditorValue = (event) => {
this.setState({code: event})
this.emitCodeLocked()
this.emitUpdateCode(event)
this.emitCodeUnlocked()
}
emitUpdateCode = throttle((event) => {
this.socket.emit("update-code", {
uuid: this.uuid,
code: event
})
}, 500)
emitCodeLocked = debounce((event) => {
this.socket.emit("code-locked", {
uuid: this.uuid
})
}, 2000, {leading: true, trailing: false})
emitCodeUnlocked = debounce((event) => {
this.socket.emit("code-unlocked", {
uuid: this.uuid
})
}, 2000)
}
@GaetanoPiazzolla
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment