Have the quantities in the orderState been recently updated?

Whenever I modify the quantity of an order item, does it result in creating a duplicate entry for that particular item in the state every time?

For instance, if the action.payload.indexNumber is 2 and action.payload.quantity is set to 100.

This snippet shows the code from orders.reducer.ts:

case OrderActions.CHANGE_QUANTITY: {
  const entities = [
    ...state.entities,
    {
      ...state.entities[action.payload.indexNumber],
      quantity: action.payload.quantity}
  ];

  return {
    ...state,
    entities
  };
}

Is there a way to avoid this duplication issue whenever I make changes to the quantity of an item?

I'd greatly appreciate any assistance on this matter. Thank you!

Answer №1

Your code is perfectly fine as it is.

When you use the spread operator (...), you are actually making a shallow copy. This means that the new object does not duplicate its members, but simply references them in a new way. This is different from deep cloning, which can be resource-intensive.

In Redux, creating new references for updated objects is not just acceptable, but necessary. Redux compares these references to determine what changes have occurred and acts accordingly.

Answer №2

Oh, I have figured out the solution! By using the slice() function, I can prevent duplication. Check out the updated code below:

case OrderActions.CHANGE_QUANTITY: {
  const entities = [
    ...state.entities.slice(0, action.payload.indexNumber),
    {
      ...state.entities[action.payload.indexNumber],
      quantity: action.payload.quantity
    },
    ...state.entities.slice(action.payload.indexNumber + 1)
  ];


  return {
    ...state,
    entities
  };
}

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

Troubleshooting React TypeScript: Resolving the Error "Argument of type ''""' is not assignable to parameter of type 'SetStateAction<undefined>'"

Currently, I am troubleshooting a React application that was extracted from a live server and now I am attempting to run it on my local machine. However, upon starting up the application locally, I encountered the following error message: Argument of ty ...

Tips for simulating behavior in express using Typescript and the Mocha library

Help with mocking 'Request' in Mocha using express with Typescript needed! Here is the current approach: describe("Authorization middleware", () => { it("Fails when no authorization header", () => { const req = { ...

Adding Intellisense functionality to my IDE: A step-by-step guide

After creating an online IDE using MEAN stack that writes code and provides server-side results, I am looking to enhance it with an intellisense feature similar to VSCode or Atom. Any recommendations on how to achieve this? ...

Having trouble utilizing the Visual Studio Code debugger in an Express.js project that uses TypeScript

My package.json file is shown below: ` { "name": "crm-backend", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev" ...

Bypass React Query execution when the parameter is null

I am facing an issue with a react query problem. I have a separate file containing all the queries: const useFetchApTableQuery = (date: string): UseQueryResult => { const axiosClient = axios.create() const fetchApTableQuery = async (): Promise<A ...

Ways to utilize multiple tsconfig files within VS Code

My project structure in Visual Studio Code is fairly common with a client, server, and shared directory setup: ├── client/ │ ├── tsconfig.json ├── shared/ ├── server/ │ ├── tsconfig.json ├── project.json The tw ...

I am facing difficulty in transmitting data from the map function within my React modal component

Although I understand the code is not great, I'm struggling with this part. My goal is to send the id data collected in the map function to the redux thunk called updatePersonal. Big thanks to all my friends who helped me out with this issue. const ...

Utilize personalized Bootstrap variables within your Angular application

I am attempting to customize the default colors of Bootstrap within my Angular project. I have established a _variables.scss file in the src directory. Within this file, I have included the following code: $primary: purple; Next, I imported my _variables ...

Encountering a issue while attempting to sign up for a function within the ngOnInit lifecycle

I keep encountering the error message "Cannot read property 'name' of undefined" when working with a basic API that returns information about vehicles. The Vehicle object has several fields: public int Id {get ;set;} public int ModelId { ...

Angular 5 encountering issue with @Injectable annotation causing TypeScript error

While trying to compile my code, I encountered the following error: import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; @Injectable() export class TaskService { constructor(private http: Ht ...

Tips on expanding properties for Material-UI components with Typescript?

My goal is to enhance the props of the Button component from Material-UI using typescript in order to pass additional props to its children. import { NavLink } from 'react-router-dom'; import { Button } from 'material-ui'; <Button ...

The data in the Angular variable is not persisting

After calling this function to retrieve an array of Articles, I noticed that the data is not being saved as expected. Take a look at my console output below. GetAll() { //return this.http.get<Array<Article>>(this.cfg.SERVER); this.http.get ...

Checkbox offering a tri-state option

Seeking help on creating a checkbox with three states. I have implemented a method to toggle between these states upon clicking. However, the issue is that this method is only triggered after the HTML changes. As a result, the checkbox's navigation be ...

Decipher and comprehend the buttons listed in the language translation document

Looking for assistance with a pipe issue. I've created the following custom SafeHtmlPipe: import { DomSanitizer } from '@angular/platform-browser'; import { Pipe, PipeTransform, SecurityContext } from '@angular/core'; @Pipe({ nam ...

An unexpected stats.js error occurred while attempting to apply custom styles to the map in AngularGoogleMaps,

My experience with Angular Google Maps has been mostly positive, except for one issue that I have encountered. When attempting to add styles to the map using the styles input attribute, I encounter an error: js?v=quarterly&callback=agmLazyMapsAPILoad ...

Redux-Form's validations may become invisible due to the triggering of the UNREGISTERED_FIELD and REGISTER_FIELD actions, both of which occur twice

In my application using React 16 and Redux-form 7, I'm encountering an issue with field validation. Whenever I change the value of a field, the UPDATE_SYNC_ERRORS action is triggered and correctly adds syncErrors to the state. However, after this, two ...

Select a random index and modify it until all unique options have been exhausted, then restart the process

My image gallery has 6 slots for images, and I have an array with a certain number of image objects: "src" : { "1x" : "/clients/Logo-1.png", "2x" : "/clients/<a href="/cdn-cg ...

"Endless loop conundrum in ngrx router

Currently, I am facing an issue while trying to integrate ngrx router-store into my application. After referencing the example app on GitHub, it seems that adding a `routerReducer` property to my application state and including the `routerReducer` from ngr ...

Having difficulty specifying the class type in Typescript

I am currently working on defining a 'Definition' type in Typescript. In this case, a Definition could be either a class constructor or an object. Here is the code snippet that illustrates my approach: if (this._isConstructor(definition)) { r ...

Tips for retrieving and storing an HTTP Post response in Angular 4 using HTML formatting

I am currently facing a challenge in Angular 4 where I am trying to retrieve and read the HTTP Post response. However, I am unable to do so because the response is in HTML format. Despite my efforts of researching various sources, I have not been able to f ...