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

The curious case of looping and peculiar Vue actions

I've been working on a project where I am looking to dynamically add more input fields upon clicking a button. My initial attempt using jQuery.append ran into issues with detecting v-model. Switching gears, I decided to try achieving the same outcom ...

What methods can I use to prevent an image from moving and trigger a specific action with the press of a key?

I'm currently teaching myself web programming and also working on improving my C++ skills. However, I am facing a challenge with Javascript. My main question is regarding how to create an "if statement" based on the location of an image. I am in the ...

Adjust the x and y coordinates of the canvas renderer

Manipulating the dimensions of the canvas renderer in Three.js is straightforward: renderer = new THREE.CanvasRenderer(); renderer.setSize( 500, 300 ); However, adjusting the position of the object along the x and y axes seems more challenging. I've ...

Using Thymeleaf within Javascript code to generate a URL?

Here is my question: The project's base URL is : The test page URL is :, and on this page, I have included a JavaScript file called datatable.packer.js using the following code: <script type="text/javascript" th:src="@{/resources/js/datatable ...

Image not located: 404 error in JavaScript

I am currently working with JavaScript and have encountered an issue. I have an array of objects that contain various data such as id, title, price, and image. I need to retrieve this data from the array in order to display it. While I am able to successfu ...

What is the best way to only buffer specific items from an observable source and emit the rest immediately?

In this scenario, I have a stream of numbers being emitted every second. My goal is to group these numbers into arrays for a duration of 4 seconds, except when the number emitted is divisible by 5, in which case I want it to be emitted immediately without ...

Retrieve information from various MongoDB collections

Greetings! I currently have a database with the following collections: db={ "category": [ { "_id": 1, "item": "Cat A", }, { "_id": 2, "item": "Cat B" ...

What is the best way to separate one dropdown area from another dropdown area?

I have two dropdown menus where, when an option with the value "other" is clicked, it generates a text area just below the dropdown menu. Both sections are functioning correctly, but I had to create separate parent wrappers for each in order to do so. How ...

Use Ramda to convert an array of objects into nested objects

As a beginner, please forgive me for asking what may be considered a naive question. I currently have an array of objects const arr = [{id: 1, name: 'Pete'}, {id: 5, name: 'John'}, {id: 3, name: 'Peter'}] and I am looking to ...

Can you explain the distinction between using this.function and making a function call in React?

I'm new to React and recently came across some code in a project that confused me. Could someone please clarify the distinction between this.function and the following function call used in a React event handling prop? <button onClick={this.clickH ...

The table fails to refresh after adding, modifying, or removing a row

Incorporating ReactJs with Material-UI, I am working on displaying a table of Car components where the display does not update after any Create, Edit, or Delete action has been performed. Below is the structure: class MainCar extends React.Component { c ...

Tips for uploading information to a web service

Issue Description:- I am attempting to access web services from a different domain (i.e. Systems are not locally connected) and encountering the following error: "Failed to load : Response for preflight is invalid (redirect)" var username = "<a href= ...

Invoking JavaScript function from an Android Activity

I have a simple JS function that is supposed to set values of some html contents, but it doesn't seem to be working properly. Here is the code for the JS function: function SetEdits(name,email,pic,date) { document.getElementById("myPic").src=pic; doc ...

Why does my counter keep incrementing by more than one every time?

As I work on creating a test in jQuery, I've encountered an issue with my counter variable count. It seems to increase by more than one when the correct answer is used. function nextQuestion(){ $('#submit').show(); $('#next&apo ...

Enlarging the current division while reducing the size of the others when hovering

Currently, I am working on a school project that involves creating a slideshow on a webpage. However, I have reached a point where I am unsure of how to proceed. Here is the progress I have made so far: body { background-color: #252525; } #wrapper { ...

Having trouble sorting data-text values that include colspan cells

Latest Update: Encountered an issue with incorrect sorting and frozen sortings when dealing with a cell containing the colspan attribute. Refer to https://jsfiddle.net/2zhjsn31/12/ where the problem arises for the date 2018-06-24 On https://jsfiddle.n ...

Firestore is failing to accept incoming data when the setDoc method is employed

I am encountering an issue with my app's connectivity to the Firestore database when attempting to utilize setDoc. The database is successfully operational for next-auth, creating records as intended. However, the problem arises when trying to enable ...

Avoid using single quotes in Postgres queries for a more secure Node.js application

Snippet from my node js code: var qry = 'INSERT INTO "sma"."RMD"("UserId","Favourite") VALUES (' + req.body.user + ',' + JSON.stringify(req.body.favourite) + ')' My problem is inserting single quotes before JSON.stringify(r ...

How can I add styling to materializecss chip elements?

When working with tags on a web page, Materializecss makes it easy. However, I have a requirement where the tags need to be of different colors based on their types. Although this is feasible, another complication arises when supporting Materializecss keyb ...

To activate a function, simply click anywhere on the body: instruction

One of my latest projects involved creating a directive that allows users to click on a word and edit it in a text box. Once edited, clicking anywhere on the body should return the word back to its updated form. html <div markdown>bineesh</div& ...