Adding elements to an array appears to cause the previously created object to react

I am encountering a situation where once I add an object to an array, it becomes reactive to any changes made.

// actions.js
export const addToCart = ({ commit }) => {
    commit('addToCart'); // successfully updates the state

    setTimeout(function () {
        commit('resetToppings');
    }, 10000);
};


// mutations.js
export const addToCart = (state) => {
    state.cart.push(state.orderItem);
};

export const resetToppings = (state) => {
    state.orderItem.toppings = [];
};


// state.js
cart: [],
orderItem: {
    quantity: 1,
    toppings: [],
},

Although orderItem is correctly added to the cart, after 10 seconds when I call resetToppings, it resets both the toppings in the cart and the orderItem.

Is there a way to prevent resetToppings from affecting anything inside the cart?

Answer №1

When you add state.orderItem to the array, it creates a reference to the object. This means that any changes made to state.orderItem will reflect in the array element because they are pointing to the same object.

To avoid this, you can push a shallow copy of the orderItem object instead:

// mutations.js
export const addToCart = (state) => {
    state.cart.push({...state.orderItem});
};

This way, each item added to the array is a unique object.


Keep in mind:

state.cart.push({...state.orderItem});

However, this method is only reliable if you do not manipulate the toppings array directly after calling addToCart. If there are cases where elements are added or removed from toppings after addToCart is called, consider cloning it as well:

state.cart.push(Object.assign({...state.orderItem}, {toppings: [...state.orderItem.toppings]}});

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

Configuring Braintree Client with JS v3 - encountering a null payment_method_nonce causing issues with form submission

I have successfully integrated Braintree into my Laravel 5.2 app using JS v2 client setup, but now I want to upgrade to v3. I have customized the code from the docs as follows: <form id="checkout-form" action="/checkout" method="post"> <div id= ...

Looking for a modular approach? Incorporate specific parts of a module into the parent component

Developing a node.js module and aiming to organize my code effectively. My goal is to have individual files/folders for different parts of the module such as authentication, users, etc. These will be required from a parent package which will then expose t ...

What is the procedure to switch the state using useState when an event is activated?

I'm trying to learn React by implementing a basic shop. One idea I had was to have multiple product images and when a user clicks on an image, it flips around to display additional information such as comments and ratings for the product. For this pr ...

Tips for formatting input boxes on the client side

Q: How can I format my textbox so that when a user enters a number, such as one, it will be displayed as 0000001? The goal is to have any number entered be shown in 7-digit format. ...

Error in NodeJs: ReferenceError - the variable I created is not defined

Encountering an issue while attempting to use a module in my router file. I have successfully required it, but now I am seeing the following error message: ReferenceError: USERS is not defined at c:\work\nodejs\router\main.js:32 ...

Is it feasible to solely utilize the "else" block for an "if...else" statement in JavaScript?

Is it possible to have an "else" block without an "if" statement in JavaScript? If so, what is the syntax for this situation? if (req.body[data].length <= maxlength[indx]); // <===== semicolon else { req.body[data] = 'ERROR: too lo ...

After my jQuery functions are executed, my CSS rules are loaded

Struggling with the communication between CSS and jQuery, I find myself torn. In CSS, my rules are often very specific, like this: div#container > div#contentLeft { //Code here } However, when I add jQuery to spice up my site, the CSS rules seem to ...

Understanding ExpressJS: Exploring the distinctions between ?, +, * in string patterns and regular expressions

Hello there! As a newcomer to Express, I've been on the hunt for a thorough explanation of string patterns with no luck. The path-to-regexp documentation has left me scratching my head. In particular, I'm grappling with this somewhat enigmatic s ...

How should one properly utilize the app and pages directories in a next.js project?

For my current next.js 13 project, I have decided to utilize the /pages directory instead of /app. Nonetheless, I recently included the app directory specifically for its new features related to dynamic sitemap rendering. Do you think this approach is app ...

React Checkbox malfunctioning: Troubleshooting and solutions

I have thoroughly researched for a solution to my issue before resorting to posting this question. Unfortunately, none of the answers I found seemed to resolve my problem. Despite trying various methods such as changing, clicking, and checking, my checkbo ...

Refreshing AngularJS: How to reload Ngtable with previous data

Currently, I am utilizing NGTable to exhibit data on my webpage. The data is stored in an array and passed through the dataset parameter. However, when I dynamically modify a value in the array, the changes are accurately reflected in the table BUT if I na ...

The form I created retrieves select options via an ajax call, but after saving, the post values are not displaying as expected

I have created a form with the following HTML code snippet: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Populate City Dropdown Using jQuery Ajax</title> <script type="text/javascript" src="h ...

Implementing a JQuery click method within a class structure

I'm having trouble getting the functionality of the .click function to work on my page unless I paste it into the browser console. In my class, this is what I have: var myClass = function(){ var toggleChecked = function(){ $('#myCheck ...

What is the process for incorporating a new task into my HTML/CSS/JavaScript to-do list application when the Enter key is pressed?

Currently, I am working on developing a to-do list application using HTML, CSS, and JavaScript. The application includes a text input field for users to enter their tasks, along with an "Add Task" button. However, I want to enhance the user experience by a ...

Python Selenium- Extract and print text from a dynamic list within a scrolling dropdown element

I am currently working on a project using Selenium and Python to extract a list of company names from a dropdown menu on a javascript-driven webpage. I have successfully managed to reveal the list of company names by clicking the navigation button, and eve ...

Use jQuery to insert the TEXT heading as an input value

Can anyone help me with copying text from a heading to an input value? Here's an example: <h2 class="customTitleHead">This is a Heading</h2> I want to transfer the text from the heading into an input field like this: <input type="tex ...

Loopback: Unable to access the 'find' property as it is undefined

I've come across a few similar questions, but none of the solutions seem to work for me. So, I decided to reach out for help. I'm facing an issue while trying to retrieve data from my database in order to select specific parts of it within my app ...

methods for retrieving nested JSON data from an API endpoint

My data has been exported in JSON format { "count":79, "stories":{ "23658975":{ "title":"NOMINATIVO", "description":"BUSDRAGHI PIERGIORGIO", "updated_at":"2013-06-16T18:55:56+02:00", "created_at":"2013-06-16T18:39:06+02:00", "du ...

Load Angular template dynamically within the Component decorator

I am interested in dynamically loading an angular template, and this is what I have so far: import { getHTMLTemplate } from './util'; const dynamicTemplate = getHTMLTemplate(); @Component({ selector: 'app-button', // templat ...

Creating a fixed sidebar that remains visible while scrolling in Next.js

Currently, I am faced with the challenge of implementing two components - a feed and a sidebar. The sidebar contains more content than it can display at once, so I want it to be able to overflow. My goal is to have the sidebar scroll along with the content ...