mirror of https://github.com/waku-org/js-waku.git
Remove listener when unmounting component
This commit is contained in:
parent
1e1ad0332c
commit
9937652105
|
@ -27,7 +27,7 @@ export default function App() {
|
||||||
const waku = await Waku.create({});
|
const waku = await Waku.create({});
|
||||||
|
|
||||||
setState(({ messages }) => {
|
setState(({ messages }) => {
|
||||||
return {waku, messages};
|
return { waku, messages };
|
||||||
});
|
});
|
||||||
|
|
||||||
waku.libp2p.peerStore.addressBook.add(
|
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) {
|
if (!state.waku) {
|
||||||
initWaku()
|
initWaku()
|
||||||
.then(() => console.log('Waku init done'))
|
.then(() => console.log('Waku init done'))
|
||||||
.catch((e) => console.log('Waku init failed ', e));
|
.catch((e) => console.log('Waku init failed ', e));
|
||||||
} else {
|
} else {
|
||||||
state.waku.libp2p.pubsub.on(RelayDefaultTopic, (event) => {
|
state.waku.libp2p.pubsub.on(RelayDefaultTopic, handleNewMessages);
|
||||||
const wakuMsg = WakuMessage.decode(event.data);
|
|
||||||
if (wakuMsg.payload) {
|
// To clean up listener when component unmounts
|
||||||
const chatMsg = ChatMessage.decode(wakuMsg.payload);
|
return () => {
|
||||||
const messages = state.messages.slice();
|
state.waku?.libp2p.pubsub.removeListener(RelayDefaultTopic, handleNewMessages);
|
||||||
messages.push(chatMsg);
|
};
|
||||||
console.log("setState on ", messages);
|
|
||||||
setState({ messages, waku: state.waku });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue