Split handleNewMessages in smaller pure functions

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

View File

@ -45,13 +45,9 @@ export default function App() {
} }
const handleNewMessages = (event: { data: Uint8Array }) => { const handleNewMessages = (event: { data: Uint8Array }) => {
const wakuMsg = WakuMessage.decode(event.data); const chatMsg = decodeWakuMessage(event.data);
if (wakuMsg.payload) { if (chatMsg) {
const chatMsg = ChatMessage.decode(wakuMsg.payload); copyAndReplace([chatMsg], stateMessages, setMessages);
const messages = stateMessages.slice();
messages.push(chatMsg);
console.log('setState on ', messages);
setMessages(messages);
} }
}; };
@ -84,14 +80,30 @@ export default function App() {
stateWaku, stateWaku,
setNick setNick
); );
const messages = stateMessages.slice(); const commandMessages = response.map((msg) => {
response.forEach((msg) => { return new ChatMessage(new Date(), command, msg);
messages.push(new ChatMessage(new Date(), command, msg));
}); });
setMessages(messages); copyAndReplace(commandMessages, stateMessages, setMessages);
}} }}
/> />
</WakuContext.Provider> </WakuContext.Provider>
</div> </div>
); );
} }
function decodeWakuMessage(data: Uint8Array): null | ChatMessage {
const wakuMsg = WakuMessage.decode(data);
if (!wakuMsg.payload) {
return null;
}
return ChatMessage.decode(wakuMsg.payload);
}
function copyAndReplace<T>(
newValues: Array<T>,
currentValues: Array<T>,
setter: (val: Array<T>) => void
) {
const copy = currentValues.slice();
setter(copy.concat(newValues));
}