I keep my chat messages in a dictionary where the key is the date and the value is a list of messages. Every time I add a message the code below runs.
Is there any way I can improve the code below so that it no longer uses JSON.parse, JSON.stringify.
on(MatchActions.AddMessage, (state: MatchState, payload: { message: Message }) => {
const messages: MessageDictionary =
JSON.parse(JSON.stringify(state.chat.messages));
const keys = Object.keys(messages)
if (keys.length > 0) {
messages[keys[keys.length - 1]].push(payload.message);
} else {
messages[getNowUtc().toString()] = [payload.message];
}
return {
...state,
chat: {
...state.chat,
messages: messages
}
}
}),
export interface Chat {
chatId: string;
name: string;
messages: MessageDictionary;
}
export interface MessageDictionary {
[dateSendUtc: string]: Message[];
}
export interface Message {
chatId: string;
accountId: string;
messageId: string;
messageText: string;
messageSendUtc: Date;
fromMe: boolean;
}
You can spread the object/dictionary
const messages = {...(state.chat?.messages || {})}
You could also make it more readable in general with const keys = Object.keys(messages)
rather than repeating it 3 times.
For a particular message
const targetKey = keys[keys.length - 1];
messages[targetKey] = [...messages[targetKey], payload.message];
There's libraries that would also help here. You could avoid a lot of this logic with immer
, or lodash/clone