From d6437352968e2ac7f024388f8eb02015c61c6318 Mon Sep 17 00:00:00 2001 From: Franck Royer Date: Fri, 7 Jan 2022 17:14:14 +1100 Subject: [PATCH] Handle incoming messages --- examples/relay-reactjs-chat/src/App.js | 27 ++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/examples/relay-reactjs-chat/src/App.js b/examples/relay-reactjs-chat/src/App.js index 6bb89e3781..3e78a21e55 100644 --- a/examples/relay-reactjs-chat/src/App.js +++ b/examples/relay-reactjs-chat/src/App.js @@ -33,6 +33,33 @@ function App() { }); }, [waku, wakuStatus]); + const processIncomingMessage = React.useCallback((wakuMessage) => { + // Empty message? + if (!wakuMessage.payload) return; + + // Decode the protobuf payload + const { timestamp, text } = proto.SimpleChatMessage.decode( + wakuMessage.payload + ); + const time = new Date(); + time.setTime(timestamp); + + // For now, just log new messages on the console + console.log(`message received at ${time.toString()}: ${text}`); + }, []); + + React.useEffect(() => { + if (!waku) return; + + // Pass the content topic to only process messages related to your dApp + waku.relay.addObserver(processIncomingMessage, [ContentTopic]); + + // `cleanUp` is called when the component is unmounted, see ReactJS doc. + return function cleanUp() { + waku.relay.deleteObserver(processIncomingMessage, [ContentTopic]); + }; + }, [waku, wakuStatus, processIncomingMessage]); + const sendMessageOnClick = () => { // Check Waku is started and connected first. if (wakuStatus !== 'Ready') return;