NgrxStore - An initial item has been added twice to the array

Currently experimenting with ngrx store and manipulating elements within an array, such as deleting, fetching, and editing, works smoothly. However, a challenge arises when inserting an object into the array for the first time, duplicating the entry unless filtered in the reducer as seen below.

State

export const initialShoppingState: ShoppingState = {
    shoppingList: [],
};

The following implementation works but perhaps filtering should not be necessary to avoid adding duplicate objects.

on(ShoppingAction.shoppingItemAdded, (state, { shoppingItem }) => {
    console.log(state);
    return ({ ...state, shoppingList: [...state.shoppingList.filter((item) => item.id !== shoppingItem.id), shoppingItem] });
}),

This approach results in the first item being added twice, while subsequent items are only added once.

on(ShoppingAction.shoppingItemAdded, (state, { shoppingItem }) => {
    console.log(state);
    return ({ ...state, shoppingList: [...state.shoppingList.concat(shoppingItem)] });
}),

Answer №1

Based on the code provided, it appears that the expected behavior is being followed and this issue cannot be resolved by the store.

The issue arises from adding an item to the array without considering uniqueness. Your solution using the filter method seems appropriate in this case.

To avoid such problems, consider structuring your state as a dictionary where each item has a unique identifier. For more information, refer to Normalizing State.

For a practical example, take a look at this link.

export const initialState: State = {
  cartItems: {},
};

export function reducer(state = initialState, action: CartActions) {
  switch (action.type) {
    case CartActionTypes.AddToCart:
      return {
        ...state,
        cartItems: {
          ...state.cartItems,
          [action.payload.sku]: (state.cartItems[action.payload.sku] || 0) + 1,
        },
      };

    case CartActionTypes.RemoveFromCart:
      return {
        ...state,
        cartItems: {
          ...state.cartItems,
          [action.payload.sku]: Math.max((state.cartItems[action.payload.sku] || 0) - 1, 0),
        },
      };

    case CartActionTypes.EmptyCart:
      return initialState;

    default:
      return state;
  }
}

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

Although the Jest tests are passing successfully, it seems that the --covering option is not detecting all

Issue summary: I have encountered an issue with Jest while trying to generate test coverage for my TypeScript class. Even though my two tests are passing, Jest seems to be unable to pick up the covered files when using the --coverage option. The output I ...

Bringing in a service from a different module in NestJS

Having an issue trying to utilize the surveyService within the voteOptionRepository. When attempting to use the route, the console displays: TypeError: this.surveyService.getSurveyById is not a function Below is my SurveyModule setup: @Module({ im ...

Tips for duplicating chosen documents utilizing AngularCLI in conjunction with WebPack for the production build

I am facing an issue with my Angular2 app when building it for production using Angular CLI and WebPack. In order to deploy the app to our production server (IIS), I need to copy certain files to the dist folder. Specifically, I require the web.config and ...

Encountering a validation error when attempting to submit the form

I am facing an issue with my form. Inside the form, I have a dropdown menu that dynamically displays a textbox upon selection. The form also includes an array feature to allow for multiple textboxes to be displayed. Despite filling in all fields with value ...

Performing simultaneous document queries within a single API in MongoDB

I am currently working with an API written in typescript and attempting to execute parallel queries for the same document by using Promise.allSettled. However, I have noticed that it is performing poorly and seems to be running sequentially instead of in p ...

Enhance user experience with Angular Material and TypeScript by implementing an auto-complete feature that allows

Currently facing an issue with my code where creating a new chip triggers the label model to generate a name and ID. The problem arises when trying to select an option from the dropdown menu. Instead of returning the label name, it returns an Object. The ...

hybrid application combining AngularJS with Angular 17 and above versions

I have been attempting to set up a hybrid environment with both AngularJS and Angular 1.7+ running side by side. I diligently followed all the guidelines and even created a custom webpack configuration to bundle my AngularJS and Angular files together. The ...

Refreshing page in Angular after authentication

Question: I am facing an issue with my signInWithEmailAndPassword function where it reloads the same page instead of redirecting to the dashboard. I have verified that the credentials are correct and match my firebase test authentication, so I suspect ther ...

The subscriber is consistently failing to return the correct value after execution, always reverting back to the default value of

I am encountering an issue with the prefillLoginId function where the value returned is always false, even though each code inside the subscription is executed. Can anyone assist me in resolving this and returning a true value? private prefillLoginId(cur ...

Creating a variable that is not defined and then converting it into

I have an issue with a function that returns an Observable. The problem is that when the function is called, the parameter works fine, but its value becomes undefined within the Observable. This is the function in question: import {Observable} from &apos ...

Encountering a node-sass problem during npm installation in my Angular project on Mac OS

While attempting to install node_modules for my Angular project on Mac OS, I encountered an issue with node-sass. My Node.js version is v16.13.2 and the node-sass version in the project is ^4.14.1. The package.json files can be viewed in image1 and image2. ...

Angular Elements generates compact, single-line HTML output

It's incredibly frustrating how browsers handle inline-block elements, creating invisible margins when placed side by side. You can experience this "bug" firsthand here: http://jsfiddle.net/8o50engu/ Interestingly, if these elements are on the same l ...

Having trouble with @Component in Angular 2+ causing an error

My application is facing a delay while loading large amounts of data, so I decided to implement a spinner. However, I encountered an issue. I referred to the following links for guidance: Pre-Bootstrap Loading Screen For Angular2 and to implement a spin ...

Display only months and years in the NgbDatepicker

Struggling with configuring the NgbDatepicker directive in my Bootstrap 4 and Angular 4 powered app. I only want to display months and years, similar to credit cards. Selecting a specific day is not important to me, I just need to choose the month and yea ...

Is it possible for a Firestore query using .where() to conduct a search with no results?

Currently, I am in the process of creating a platform where users can upload past exams. Each document contains various fields such as teacher, year, and class, all stored in cloud Firestore. To filter the data by teacher, I am using the .where("Teacher" ...

Accessing and sending only the body part of an HTTP response in Angular 7 test cases: A comprehensive guide

Currently, I am working on creating unit test cases in Angular 7 for a Component that utilizes an asynchronous service. This is the content of my component file: submitLoginForm() { if (this.loginForm.valid) { // send a http request to save t ...

Storing Images in MongoDB with the MEAN Stack: A Guide using Node.js, Express.js, and Angular 6

I am currently working on developing a MEAN Shop Application, and I have encountered an error while attempting to store the product image in MongoDB. typeError: cannot read the property 'productimage' of undefined Below is the route function fo ...

Combining Vue-Test-Utils with TypeScript typings for wrapper.vm

So, I ran into an interesting situation. Has anyone ever worked with typescript + vue-test-utils and attempted to change a value for testing purposes like this: wrapper.vm.aCoolRefValueToManipulate = 'something much cooler'? I gave it a shot, a ...

A step-by-step guide on configuring data for aria's autocomplete feature

Currently, I am implementing aria autocomplete and facing an issue while trying to populate data from the server into the selection of aria autocomplete. I have tried setting the selected property of the aria autocomplete object, but it doesn't seem t ...

The child component is receiving undefined props, yet the console.log is displaying the actual values of the props

Struggling to implement a Carousel in my Gatsby-based app, I encountered an issue with passing props from the Parent to Child functional component. The error message "TypeError: props.slide is undefined" was displayed, but upon checking the console logs, i ...