From 9937652105b4cde6fac6fd05973932544379124d Mon Sep 17 00:00:00 2001 From: Franck Royer Date: Thu, 22 Apr 2021 11:09:10 +1000 Subject: [PATCH] Remove listener when unmounting component --- web-chat/src/App.tsx | 30 +++++++++++++++++++----------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/web-chat/src/App.tsx b/web-chat/src/App.tsx index a18260238c..2cf1554022 100644 --- a/web-chat/src/App.tsx +++ b/web-chat/src/App.tsx @@ -27,7 +27,7 @@ export default function App() { const waku = await Waku.create({}); setState(({ messages }) => { - return {waku, messages}; + return { waku, messages }; }); waku.libp2p.peerStore.addressBook.add( @@ -39,21 +39,29 @@ export default function App() { } + const handleNewMessages = (event: { data: Uint8Array }) => { + const wakuMsg = WakuMessage.decode(event.data); + if (wakuMsg.payload) { + const chatMsg = ChatMessage.decode(wakuMsg.payload); + const messages = state.messages.slice(); + messages.push(chatMsg); + console.log('setState on ', messages); + setState({ messages, waku: state.waku }); + } + + }; + if (!state.waku) { initWaku() .then(() => console.log('Waku init done')) .catch((e) => console.log('Waku init failed ', e)); } else { - state.waku.libp2p.pubsub.on(RelayDefaultTopic, (event) => { - const wakuMsg = WakuMessage.decode(event.data); - if (wakuMsg.payload) { - const chatMsg = ChatMessage.decode(wakuMsg.payload); - const messages = state.messages.slice(); - messages.push(chatMsg); - console.log("setState on ", messages); - setState({ messages, waku: state.waku }); - } - }); + state.waku.libp2p.pubsub.on(RelayDefaultTopic, handleNewMessages); + + // To clean up listener when component unmounts + return () => { + state.waku?.libp2p.pubsub.removeListener(RelayDefaultTopic, handleNewMessages); + }; } });