When using React, I noticed that adding a new product causes its attributes to change after adding another product with different attributes on the same page

Imagine you are browsing the product page for a Nike T-shirt. You select black color and size S, adding it to your cart. The cart now shows 1 Nike T-SHIRT with attributes color: black, size: S. However, if you then switch to white color and size M on the same page, the previously added shirt's attributes change to color: white and size: M. So now the cart has 2 T-SHIRTS with size: M and color: black. Where am I going wrong?

class PDP extends Component {
      state = {
        currentProduct: this.props.location.state,
        selectState: [],
        testObj: {},
      } 
    render() {
    let product = this.state.currentProduct;
    let handleChange = (evt,attribute) => {
            const test = Object.assign({}, product);
            this.state.testObj[attribute] = evt.target.value;
            this.state.selectState.push(this.state.testObj);
            let selectedAttributes = [...new Set(this.state.selectState)];
            test.selectedAttributes = selectedAttributes;
            this.setState((state) => ({
              currentProduct: test
            }))
          } 
    
    <button className="addToCart" onClick={() => this.props.data.addProduct(this.state.currentProduct)}>ADD TO CART</button>
    
     addProduct = (product) => {
        this.setState((state) => ({
          cart: state.cart.concat(product),
        }))
       
      } 

Answer №1

From the code snippet provided, it appears that there may be an issue related to cloning the product object within the handleChange function.

You can test this by replacing Object.assign with the following code:

const clonedProduct = JSON.parse(JSON.stringify(product));

Answer №2

It appears that the issue lies within this specific line of code:

this.state.testObj[attribute] = evt.target.value;

Due to objects being passed by reference, modifying any attribute in testObj (such as the color) will affect all other references as well.

To address this, you can try the following solution:

let handleChange = (evt, attribute) => {
  const test = Object.assign({}, product);
  this.state.testObj[attribute] = evt.target.value;
  const testObj = Object.assign({}, this.state.testObj);
  this.state.selectState.push(testObj);
  let selectedAttributes = [...new Set(this.state.selectState)];
  test.selectedAttributes = selectedAttributes;
  this.setState((state) => ({
    currentProduct: test,
  }));
};

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

Refreshing a HTML table by retrieving data from a session variable

I'm still learning the ropes when it comes to JSP, jQuery, and AJAX. I have a JSP page that utilizes a table populated with values from a List variable stored in session. Below is the code snippet: <table id="someData" class="display" width="95%"& ...

What are the steps to integrate and utilize DefinePlugin within your webpack configuration?

Hello, I'm currently trying to implement the DefinePlugin in order to update the version number and ensure that my JavaScript refreshes after a new build is released. Unfortunately, I am encountering issues with getting DefinePlugin to work properly. ...

Is there a way to determine if a specific string matches a value within an object?

Within my codebase, there exists an object named "codes": var codes = { code1: 'test1' code2: 'test2' } I am looking to determine if this object possesses a specific property and then display the result in the console. if(inp ...

Modify Bootstrap Card Styling Using JavaScript

When the clock strikes certain evening hours on my website, the Bootstrap card's default light style no longer fits the dark theme. I've attempted to switch the card to a dark style by tying in some JavaScript code, but it's not quite doing ...

Tips for adjusting the size of nav-pills when collapsing with bootstrap 5

I'm attempting to utilize Bootstrap to create active classes that display a nav-pill/container around the active section of my webpage. It works well on larger screens, but on smaller screens with the hamburger menu active, the nav-pill stretches acro ...

"Trying to activate a hover effect on a div using JQuery, but it's not functioning

Is there a way to make these divs animate each time I hover over them? Currently, the animation only works once and does not repeat when hovering again. Can anyone provide guidance on how to achieve this? function Rotate() { $('#gear1,#gear2,#gea ...

Ensuring that the bootstrap5 column extends all the way to the footer

Looking to display a specific email address mailbox for a project. The goal is to have the 'Mail Card List' scrollable instead of extending beyond the page. Tried using 'max-height:;' CSS, but it sets a fixed height. Seeking a variable ...

Reduce the combined character value of the title and excerpt by trimming the excess characters

I am seeking a solution to trim the total character count of a post title and excerpt combined. Currently, I can individually adjust the excerpt through theme settings and the post title using JavaScript. However, due to varying title lengths, the height ...

Undefined elements in an array of objects in Javascript

I've been working on creating an array of objects in JavaScript, but I'm facing an issue when attempting to print the array to the console in Chrome. It keeps returning undefined unless I print the array right after pushing new elements into it. ...

Correct validation is not achieved when the "!" symbol is used in the matches function

I am working on a React and Next.js project where I am using Formik for handling forms and Yup for validations. One specific input field requires some validations to be performed. This field must be required, so if the user does not enter any information, ...

Issue with PHP redirection not functioning as expected upon submission

Thank you for taking the time to offer assistance. I am encountering an issue with a basic HTML contact form that utilizes a PHP file for processing. The form's method is set to post and it directs its action to a PHP file. Upon completion of the PHP ...

Having issues with image hover and click functionality

My website has an image with the cursor set to pointer and a function that should show a hidden element when clicked. However, it's not working at all. When I hover over it or click on it, nothing happens. Here is a screenshot of the issue along with ...

How can you use plain javascript to drag and drop the cross sign within the box in the grid?

Creating a grid in HTML where clicking on a box will draw an x sign and remove it if clicked again. View the DEMO here. Challenge Description:- I am now looking to implement dragging the cross (x) sign to another grid within the box, but cancelling the ...

Obtain Python script output displayed in HTML format

I am currently working on developing Python scripts that can be utilized by front-end HTML+CSS developers for websites. To test the feasibility of this approach, I have written a basic script that makes use of parse.com as the backend. The script retrieves ...

Issue with delayed chaining of class addition and removal in JQuery not functioning as expected

Here is the code snippet: $(document).ready(function () { $('.current-visitors').delay(3000).queue(function () { $(this).addClass('show').delay(1000).queue(function () { $(this).removeClass('sho ...

Tips for showing the chart title and subtitle using "vue-google-charts" library by devstark: Where to position them - top or bottom?

Utilizing the resource available at https://www.npmjs.com/package/vue-google-charts The title is not being displayed on the chart. Is there a way to show it either above or below the chart? I attempted adding "display=true" with the option "title" and fo ...

What is the best way to iterate over an associative array and display the contents as a list?

After successfully setting up my initial array, I have been struggling to loop through each row and display the three columns/elements in a tag. Here is the var_dump of my array: array(27) { [3]=> array(3) { ["id"]=> string(3) "295" ["title"]=gt ...

Examining the Similarities Between Two Arrays using ng-repeat

I am attempting to generate multiple checkboxes using ng-repeat from Array1, and I want to apply the "checked" attribute (using ng-checked) to specific checkboxes based on whether there is a match in Array2. Here are the elements in array1 within the cont ...

Add information from a filled data chart

I'm seeking your assistance with a challenge I am facing. In Form1.php, I have extracted data from the database (flock id, house, breed) which populates one table row. The issue is that this form involves two tables in the database. flock id, house, ...

The function Getter is expected, but an error has occurred with "getters.doubleCounter" returning a value of 20 in VUEX

Currently, I am diving into the world of Vuex and encountering some challenges along the way. In my attempt to create a getter on my vuex instance, I am facing an error when trying to display data from one of my components: The getter should be a functi ...