Created
May 9, 2019 14:29
-
-
Save Jotschi/f935bb2c1fa2bc71abbed8448846556f to your computer and use it in GitHub Desktop.
Websocket Gentics Mesh Snippets
This file contains 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 EventBus from 'vertx3-eventbus-client'; | |
import { useEffect } from 'react'; | |
let eb = new EventBus("/api/v1/eventbus") | |
eb.enableReconnect(true); | |
let callbacks = []; | |
let espCallbacks = []; | |
eb.onopen = function () { | |
console.log("Connect eventbus"); | |
registerEvent("mesh.node.updated", callbacks); | |
registerEvent("mesh.node.created", callbacks); | |
registerEvent("mesh.node.deleted", callbacks); | |
registerEvent("custom.event", espCallbacks); | |
} | |
function registerEvent(eventName, callbacks) { | |
eb.registerHandler(eventName, function (error, message) { | |
callbacks.forEach(cb => cb()); | |
console.log('Received a message: ' + JSON.stringify(message)); | |
}); | |
} | |
export function useWebsocketESPBridge(callback) { | |
useEffect(() => { | |
espCallbacks.push(callback); | |
console.log("Mount ESP"); | |
return () => { | |
var index = espCallbacks.indexOf(callback); | |
if (index > -1) { | |
espCallbacks.splice(index, 1); | |
} | |
console.log("Unmount ESP"); | |
} | |
}, []); | |
} | |
export default function useWebsocketBridge(callback) { | |
useEffect(() => { | |
callbacks.push(callback); | |
console.log("Mount"); | |
return () => { | |
var index = callbacks.indexOf(callback); | |
if (index > -1) { | |
callbacks.splice(index, 1); | |
} | |
console.log("Unmount"); | |
} | |
}, []); | |
} |
This file contains 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 useWebsocketBridge from '../eventbus'; | |
export default function ScreenView({ match }) { | |
const id = match.params.id; | |
const [screenResponse, setScreenResponse] = useState(); | |
useWebsocketBridge(async () => { setScreenResponse(await getScreen(id)) }); | |
useEffect(() => { | |
getScreen(id).then(setScreenResponse); | |
}, []); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment