Remove listener when unmounting component

This commit is contained in:
Franck Royer 2021-04-22 11:09:10 +10:00
parent 1e1ad0332c
commit 9937652105
No known key found for this signature in database
GPG Key ID: A82ED75A8DFC50A4
1 changed files with 19 additions and 11 deletions

View File

@ -39,21 +39,29 @@ export default function App() {
}
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 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);
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, handleNewMessages);
// To clean up listener when component unmounts
return () => {
state.waku?.libp2p.pubsub.removeListener(RelayDefaultTopic, handleNewMessages);
};
}
});