Split useEffect calls

Better React practice.
This commit is contained in:
Franck Royer 2021-06-04 15:20:36 +10:00
parent ad4101f612
commit 0d00328715
No known key found for this signature in database
GPG Key ID: A82ED75A8DFC50A4
1 changed files with 26 additions and 17 deletions

View File

@ -86,8 +86,17 @@ export default function App() {
localStorage.setItem('nick', nick); localStorage.setItem('nick', nick);
}, [nick]); }, [nick]);
// Waku: Start, process messages, send messages
useEffect(() => { 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) => { const handleRelayMessage = (wakuMsg: WakuMessage) => {
console.log('Message received: ', wakuMsg); console.log('Message received: ', wakuMsg);
const msg = Message.fromWakuMessage(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 ( const handleProtocolChange = async (
waku: Waku, waku: Waku,
{ peerId, protocols }: { peerId: PeerId; protocols: string[] } { peerId, protocols }: { peerId: PeerId; protocols: string[] }
@ -118,13 +135,6 @@ 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( stateWaku.libp2p.peerStore.on(
'change:protocols', 'change:protocols',
handleProtocolChange.bind({}, stateWaku) handleProtocolChange.bind({}, stateWaku)
@ -137,7 +147,6 @@ export default function App() {
handleProtocolChange.bind({}, stateWaku) handleProtocolChange.bind({}, stateWaku)
); );
}; };
}
}, [stateWaku]); }, [stateWaku]);
return ( return (