Eliminate the usage of JSON.stringify in the Reducer function

I have a system where I store chat messages in a dictionary with the date as the key and a list of messages as the value. Whenever a new message is added, the following code snippet is executed.

Is there a way to enhance the existing code to eliminate the use of JSON.parse and JSON.stringify?

on(MatchActions.AddMessage, (state: MatchState, payload: { message: Message }) => {
    const messages: MessageDictionary = { ...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;
}

Answer №1

If you want to extend the object/dictionary

const conversations = {...(state.chat?.conversations || {})}

To make the code more readable, consider using

const keys = Object.keys(conversations)
instead of repeating it multiple times.

For a specific conversation

const latestKey = keys[keys.length - 1];

conversations[latestKey] = [...conversations[latestKey], newMessage];

There are libraries that can simplify this process. You might find tools like immer or lodash/clone useful in avoiding unnecessary complexity.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the Contrasts: ng add <package name> versus npm install <package name> in Angular 6

With the recent release of Angular6, a new command called ng add has been introduced. I am curious to know what sets this apart from the traditional npm install <package> and ng add <package>. ...

Creating a custom definition file for TypeScript

Currently, I am facing an issue with a third-party library that provides global functions similar to jQuery ($ .functionName()), but unfortunately there is no definition file available. Due to this, my attempt to write my own file has been unsuccessful as ...

Angular mat-select is having difficulty displaying options correctly on mobile devices or devices with narrow widths

In my Angular project, I've encountered an issue with mat-select when viewing options on mobile or low-resolution screens. While the options are still displayed, the text is mysteriously missing. I attempted to set the max width of the mat-option, but ...

Guide to Rolling a Set of 5 Dice

I am looking to develop a game involving 5 dice. I have already created a function to roll one die using a random method, but I am unsure how to extend this functionality to the remaining four dice without having to create a separate method for each one. ...

The 'setState' property is not found on the 'Window' type

I am encountering an issue with the code snippet in my index.tsx file let state = {}; window.setState = (changes: any) => { state = Object.assign({}, state, changes); ReactDOM.render(<App {...state} />, document.getElementById("root")); ...

Angular 5's recursive directives in dynamic modules without any circular dependencies

I've been experimenting with loading dynamic templates into my Angular 5 app. My first attempt was following the examples in the official Angular documentation, but I quickly realized that they only cover loading static components dynamically. Next, ...

Decoding the HTML5 <video> tag using the html-react-parser library

I'm working on a NextJS V13 app where I need to display HTML content fetched from a CMS. Instead of using dangerouslySetHtml, I opted for the html-react-parser package to parse the HTML and replace certain embedded tags like <a>, <img>, an ...

Using Angular to make a request to a NodeJS+Express server for a simple GET operation

I need help with making a successful GET request from my Angular component to a NodeJS+Express server. someComponent.ts console.log("Before"); // send to server console.log(this.http.get('/email').map((res:Response) => { console.log(" ...

Filtering data in TypeScript from a different component with the filter function

Currently, I am in the process of creating a filter function for a table. The table header and table body are separate components - with one responsible for filtering the data and the other for displaying it. User input is stored in the Table Header Compo ...

Creating a loading spinner with the help of an rxjs BehaviorSubject

After creating a loading spinner component for my angular 4 application to display during AJAX calls, I encountered an issue when trying to implement it with a subscription to a BehaviorSubject. This question is similar to how to show a spinner until data ...

Ways to invoke a slice reducer from a library rather than a React component

I've been working on a React application using the React Boilerplate CRA Template as my foundation. This boilerplate utilizes Redux with slices, which is great for updating state within a React component. However, I'm facing a challenge when try ...

The UI in PrimeNG dropdown does not reflect changes made with patchValue()

Currently, I am working on a reactive form that includes a few fields - three dropdowns and one calendar. These fields are all PrimeNG components. Interestingly, all fields except for the project field successfully update their values in the user interface ...

Can child components forward specific events to their parent component?

I created a basic component that triggers events whenever a button is clicked. InnerComponent.vue <template> <v-btn @click="emit('something-happened')">Click me</v-btn> </template> <script setup lang=" ...

Is it possible for Angular to retrieve information from one JSON file but not another?

After updating the names in the code to reflect the current ones, I would greatly appreciate any help or suggestions! The json file has been provided, so there's not much additional setup required. Just a heads up: I haven't created a service fi ...

Reducing the Angular version from 11 to 9

{ "name": "project-learn-web", "version": "1.0.0", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", " ...

Navigating through Objects in Angular 9

I am facing a challenge in Angular 9/Typescript while trying to iterate through the object response from my JSON data. Despite searching for solutions, I haven't found any that work for me. In my JSON, there is a section called "details" which contain ...

The ability to choose only one option in a checkbox within a grid view column

In my grid view, I have a checkbox in the last column. I am trying to ensure that only one row can be selected at a time. <tr *ngFor="let permit of PermitDetails" (click)="GoByClick(permit)"> <td style="text-align: center">{{permit.TVA_BAT ...

Is it possible to use the HostListener in Angular 7 to detect any scroll event occurring on a specific element within a webpage?

I am developing a breadcrumb bar component in Angular 7 that should dynamically hide and show based on user scrolling behavior. To achieve this, I created a directive to track the scroll position of the container element. While my code for capturing the s ...

Find out if a dynamically imported component has finished loading in Nextjs

Here is a simplified version of my current situation import React, { useState } from 'react'; import dynamic from 'next/dynamic'; const DynamicImportedComponent = dynamic(() => import('Foo/baz'), { ssr: false, loading ...

Angular does not wait for the backend service call response in tap

Does anyone have a solution for subscribing to responses when the tap operator is used in a service? edit(status) { dataObj.val = status; // call post service with status.. this.service .update(dataObj) .pipe(takeUntil(this._n ...