Last active
May 17, 2021 14:47
-
-
Save GaetanoPiazzolla/5b2be57640cb47c0ef0c394ef1f8fe1e to your computer and use it in GitHub Desktop.
Central part of Client of DirectCode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
related to medium article:
https://medium.com/geekculture/how-to-build-a-web-app-to-share-code-live-with-node-js-and-socket-io-b37c23ec0862