From 0d0032871579b89bb192d9bea40cd474e21c1ac7 Mon Sep 17 00:00:00 2001 From: Franck Royer Date: Fri, 4 Jun 2021 15:20:36 +1000 Subject: [PATCH] Split useEffect calls Better React practice. --- examples/web-chat/src/App.tsx | 43 +++++++++++++++++++++-------------- 1 file changed, 26 insertions(+), 17 deletions(-) diff --git a/examples/web-chat/src/App.tsx b/examples/web-chat/src/App.tsx index b4a3a71d6b..db8a8df8db 100644 --- a/examples/web-chat/src/App.tsx +++ b/examples/web-chat/src/App.tsx @@ -86,8 +86,17 @@ export default function App() { localStorage.setItem('nick', nick); }, [nick]); - // Waku: Start, process messages, send messages useEffect(() => { + if (stateWaku) return; + + initWaku(setWaku) + .then(() => console.log('Waku init done')) + .catch((e) => console.log('Waku init failed ', e)); + }, [stateWaku]); + + useEffect(() => { + if (!stateWaku) return; + const handleRelayMessage = (wakuMsg: WakuMessage) => { console.log('Message received: ', wakuMsg); const msg = Message.fromWakuMessage(wakuMsg); @@ -96,6 +105,14 @@ export default function App() { } }; + stateWaku.relay.addObserver(handleRelayMessage, [ChatContentTopic]); + + return; + }, [stateWaku]); + + useEffect(() => { + if (!stateWaku) return; + const handleProtocolChange = async ( waku: Waku, { peerId, protocols }: { peerId: PeerId; protocols: string[] } @@ -118,26 +135,18 @@ export default function App() { } }; - if (!stateWaku) { - initWaku(setWaku) - .then(() => console.log('Waku init done')) - .catch((e) => console.log('Waku init failed ', e)); - } else { - stateWaku.relay.addObserver(handleRelayMessage, [ChatContentTopic]); + stateWaku.libp2p.peerStore.on( + 'change:protocols', + handleProtocolChange.bind({}, stateWaku) + ); - stateWaku.libp2p.peerStore.on( + // To clean up listener when component unmounts + return () => { + stateWaku?.libp2p.peerStore.removeListener( 'change:protocols', handleProtocolChange.bind({}, stateWaku) ); - - // To clean up listener when component unmounts - return () => { - stateWaku?.libp2p.peerStore.removeListener( - 'change:protocols', - handleProtocolChange.bind({}, stateWaku) - ); - }; - } + }; }, [stateWaku]); return (