Home > Back-end >  Remove JSON.stringify from Reducer
Remove JSON.stringify from Reducer

Time:08-21

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;
}

CodePudding user response:

You can spread the array

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.

CodePudding user response:

You are converting from json to string then you convert string to json again. I think that you remove JSON.stringify and JSON.parse in constant 'messages'

  • Related