Changes made to one order's information can impact the information of another order

Currently, I am in the process of developing a unique shopping cart feature where users input a number and a corresponding product is added to a display list. Users have the ability to adjust both the price and quantity of the products, with the total price automatically updating upon modification.

The challenge I am encountering involves generating two "order" divs when I enter multiple numbers (e.g., 1234 and 2345). Each div contains information on price and quantity for user customization. However, altering the price or quantity impacts the total amount for both orders instead of just the specific one being modified, creating a cross-contamination effect between the two. How can I rectify this issue within the feature?

For reproducibility purposes, here is a link to a stackbiltz showcasing the problem (Please excuse the layout imperfections as it is a minimal sample): https://stackblitz.com/edit/angular4-nsy31g

Below is the code snippet:

component:

 // Relevant component code goes here 

html:

<p>Essential calculations</p>
// HTML rendering code here

In essence, the main issues are:

1) Modifying the retail price or quantity should solely affect the respective order without influencing other items in the list.

2) The total amount must accurately reflect the combined sum of all orders present in the list.

Your assistance on mitigating these challenges would be greatly appreciated! Thank you!

Answer №1

It appears that there are a few issues present. I have addressed and resolved them in the following link: https://stackblitz.com/edit/angular4-onsxlh

The specific problems include:

  1. There is a repetition of the same object being added when a new order is appended to the orderDetails array, resulting in modifications affecting all instances:

    this.orderDetails.push(this.order);

To rectify this issue, it is necessary to clone the object if you intend for this.order to remain as the default object:

this.orderDetails.push({...this.order});

By implementing this change, a cloned version of the object will be added instead of the original one.

  1. Upon calling updateTotal, the parameter indx specifying the index of the modified order is never utilized. Instead, you seem to be altering global variables within the component indiscriminately, leading to consistent values regardless of the edited order. Furthermore, the template displays the extendedPrice variable for every item, resulting in uniform values.

To resolve this issue, ensure that you render the value of

order._extendedPrice</code to display the cost of each individual item. Additionally, within the <code>updateTotal
function, make sure to update the attributes of the current order rather than global variables:

updateTotal(retailPrice: number, number: number, indx: number) {
  const order = this.orderDetails[indx];
  order._retailPrice = retailPrice;
  order._quantity = number;
  order._extendedPrice = retailPrice * number;
  this.getTotal();
}
  1. Lastly, the total sum of all orders is not being calculated. To address this, I have included the method getTotal, which utilizes reduce to accumulate the extended prices of each order.

Following these adjustments, the functionality should now align with expectations.

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

Error message: The 'node_modules' directory is not found after installing

During class today, I faced a problem. I was demonstrating to my students how to install and use gulp.js using a projector. I successfully installed node.js and gulp.js globally with npm install -g gulp without any issues. However, when attempting to ins ...

Nested SetTimeout function fails to execute

Attempting to implement a button that provides feedback for its actions, I am faced with a challenge in Angular. After sending a put request to the server, the button's state changes to show this action. Upon receiving a response, the button's st ...

Choosing the relevant kendo row on two different pages

I am facing a situation where I have a Kendo grid displayed on a dashboard page. Whenever a user selects a row in this grid, I need to load the same row in another Kendo grid on a separate ticket page to showcase the details of that particular ticket. The ...

Clearing the Redux state in my app upon exiting the page

I've come across similar inquiries, but none of them quite match my situation. When a user clicks on one of the buttons in my app, it triggers a get request to fetch data and then displays that data on the screen. However, the issue arises when I nav ...

The function client.guilds.find cannot be located

Hey there! I've been tasked with working on a Discord bot that requires several dependencies to function properly. I've installed the necessary dependencies and attempted to run the bot using 'forever -o out.log bot.js'. However, I enc ...

Creating a navigation bar that stays fixed at the top of

Hey there, currently I am utilizing a combination of jquery and css to affix my navigation menu at the top when scrolled. However, the problem is that my navigation menu is positioned beneath a div with a height set in viewport units (vh). The jquery scr ...

When working with Angular 5, the question arises: how and where to handle type conversion between form field values (typically strings) and model properties (such

As a newcomer to Angular, I am struggling with converting types between form field values (which are always strings) and typed model properties. In the following component, my goal is to double a number inputted by the user. The result will be displayed i ...

TypeError: Unable to access the 'classify' property of an object that has not been defined (please save the ml5.js model first)

In my React app, I have set up ml5.js to train a model by clicking on one button and make predictions with another. However, I encounter an error when trying to test the model for the second time: TypeError: Cannot read property 'classify' of und ...

Excluding node modules when not included in tsconfig

Within my Angular project, there is a single tsconfig file that stands alone without extending any other tsconfigs or including any additional properties. Towards the end of the file, we have the following snippet: "angularCompilerOptions": { ...

React Application Issue: Unable to successfully redirect to the homepage upon logging in

Attempting to create a web application with the MERN stack is causing some trouble when trying to redirect users to the home page post-login. Here's how it should ideally function: User inputs login details The server validates these details and gene ...

The international telephone input library's "grunt img" command is malfunctioning

I am currently utilizing intl-tel-input to develop a control for displaying mobile numbers. Since the flags are quite small, I am in need of enlarging them. A reference for this can be found here: https://codepen.io/jackocnr/full/ONXWgQ To achieve this, ...

Presenting two arrays simultaneously creates angular duplicates

Encountering an issue while trying to display two arrays containing channel information: List of channels List of subscriptions that users have opted for. channels = [ { "id": 1, "name": "arte", "service&q ...

React Native ScrollView with a custom footer that adjusts its size based on the content inside (

I've implemented the code below to ensure that the blue area in image 1 remains non-scrollable when there is sufficient space, but becomes scrollable when space is limited. However, I'm facing an issue where the ScrollView component is adding ext ...

Display data in Highchart legend only if it has values

In a unique scenario, I am required to compare various items and display the results in a chart. The user inputs two, three, or four article IDs and receives the corresponding data displayed in a chart. The issue arises when the user enters only two or th ...

What is the best way to update the value of a Material Angular select to match its label in TypeScript?

Is there a way to reset the value of this select element back to <mat-label>Select Member</mat-label> in TypeScript when a specific event occurs? I am currently unable to find a solution on the TypeScript side. Any advice would be appreciated ...

javascript show and hide navigation bar

I am currently working on a HTML menu that includes a button to open it and an unordered list : <nav class="menu"> <button> <h1>Menu</h1> </button> <ul class="mylist" ...

I am encountering an issue with the useRef function not properly detecting visibility

I'm looking to incorporate a fade-in animation into my React div as I scroll and reach a specific section. Unfortunately, the useEffect function that is supposed to detect the scrolling behavior seems to be malfunctioning and I can't figure out w ...

Change this npm script into a gulp task

I have a script in npm that I would like to convert into a gulp task. "scripts": { "lint": "eslint .", "start": "npm run build:sdk && node .", "posttest": "npm run lint && nsp check", "build:sdk": "./node_modules/.bin/lb- ...

Is there a way to export a variable that has been declared within a function component in React Js?

I am currently developing a React app and I need to export the RoomPricelist1 & FacilityPricelist1 variables. I have assigned values to these variables within a function component but when I try to import them into another function component, they are sh ...

Develop a nodejs script to make a request using a curl or similar method

Can anyone help me figure out how to replicate the functionality of this OpenSSL command using Node.js or curl? The command is: openssl s_client api-prd.koerich.com.br:443 2> / dev / null | openssl x509 -noout -dates. I have been unsuccessful in my at ...