Taking out one item from a container results in the removal of that same item from another identical container as well

I am facing an issue where I have two objects that contain the same data. I need to remove an item from one of the objects without affecting the other. However, when I try to use the splice method on one object, it also affects the other one and I end up losing the item in both objects.

<button @click="deleteData(0)" />

export default {
    data() {
        return {
            arrayA: [],
            arrayB: []
        }
    },
    methods: {
        async initData() {
            const { data: response } = await this.$store.dispatch("getData", { id: this.$route.params.id })

            this.arrayA = response
            this.arrayB = response
        },

        deleteData(indexOfItem) {
            console.log("arrayA & arrayB before splice: ", this.arrayA, this.arrayB);
            // arrayA & arrayB before splice : [{...}, {...}], [{...}, {...}]

            this.arrayA.splice(indexOfItem, 1);

            console.log("arrayA & arrayB after splice :", this.arrayA, this.arrayB);
            // arrayA & arrayB after splice :  [{...}], [{...}]
        }
    }
}

Answer №1

In vue.js, the reactivity feature causes changes in one object to affect everything else that was declared with a reference.

For example: Suppose you have an objectA with your data and declare objectB = objectA. Any changes made to objectA will also impact objectB.

To avoid this: If you need objectB to hold the same data as objectA, but independently, you can use the following method:

objectB = JSON.parse(JSON.stringify(objectA));

Keep in mind that using this approach means that objectB will not react to changes made to objectA.


UPDATE: Explanation of your code snippet

Since you provided the code below:

data() {
  return { 
    a: [],
    b: [] 
  }
  }, 
methods: { 
  getData() { 
    const response = (request to retrieve the data...); 
    this.a = response.data; 
    this.b = response.data; 
  } 
}

Both a and b are reactive and share the same data source. Therefore, altering the content of either a or b will result in changing the source of data, affecting both variables simultaneously.

An alternative approach would be:

data() {
  return { 
    a: [],
    b: [] 
  }
  }, 
methods: { 
  getData() { 
    const response = (request to retrieve the data...); 
    this.a = response.data; 
    this.b = JSON.parse(JSON.stringify(this.a)); 
  } 
}

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 AJAX in Code Igniter is throwing an error due to an undefined index 'id

I'm encountering an issue when calling a function in AJAX, as it shows the error message "Undefined index: id". Strangely, if I have only one button in the view, the function works fine. However, when there are two buttons present, the error occurs. W ...

Updating the store state in Vuex using an asynchronous request with Axios in a Vue component

I have been working on a project that involves vue, vuex, and webpack. I have set up a Vue instance and imported a vue component along with a vuex store. Both the component and store are successfully registered to the Vue instance. I utilized axios to make ...

Implementing checkboxes for each API data in JavaScript

I am fairly new to this and I am currently working on a to-do list. I want to include a checkbox next to each item from the API to indicate whether it has been completed or not. <script type="text/javascript"> fetch('http://localhos ...

How can you use jQuery to display an image when hovering over text?

Looking for a tutorial or script that displays an image when hovering over HTML text with the mouse? ...

What steps are needed to obtain the Access Token and avoid the CORS Policy in a Spring Boot application?

As part of my project, I integrated Oauth2 authentication into a GraphQL/Spring Boot API and need to access it from a VueJS app using Apollo Client. While I can successfully interact with the API using Postman, I encountered a CORS error in Chrome: ...

Verify the validity of the user's input

Using knockout.js and knockout.validation, I have created a book view model with properties for the author's name and book title: function BookViewModel(bookObj) { var self = this; self.AuthorName = ko.observable(bookObj.AuthorName) ...

In JavaScript, learn how to trigger a statement only when two specific events occur simultaneously

<html> <head> <style> div{ border: 1px solid black; width: 500px; height: 500px; } </style> <script> window.onload = function(){ document.body.onmousedown = function ...

Received undefined response from Axios.get() request

While working with the code below, I encountered an issue. The axios get request from await axios.get('/products/api') is functioning properly and I can see the data in the console. However, for await axios.get('/users/api'), 'Unde ...

Using jQuery to manage multiple page requests on a single page

In my current project using Codeigniter, I encountered a challenge of loading multiple paginations on one page. After exploring various forums and websites, I decided to implement multiple methods and views to achieve this using jQuery. The code snippet I ...

Exploring a collection of objects housed in a json document

Currently, I'm looking to retrieve a collection of objects using JavaScript from a JSON file that resides on my website. While I could easily embed the array of objects directly into my JavaScript code, I am interested in understanding how to work wit ...

Display a fixed three levels of highchart Sunburst upon each click in Angular8

Looking to create a dynamic sunburst highchart that displays three levels at a time while allowing interactive drilling. For instance, if there are 5 levels, the chart should initially show the first three levels. When clicking on level 3, levels 2, 3, and ...

Tips for unchecking a checkbox when another checkbox is checked in Angular

My table displays a list of deleted items. Users have the option to either recover the item or delete it permanently. I am seeking assistance in ensuring that only one checkbox is checked in a table row, and unchecking other checkboxes if the user tries t ...

Unable to choose an item from b-dropdown in vuejs

Greetings! I am currently working on creating a basic dropdown menu using bootstrap-vue in vuejs. The code snippet in my component looks like this : <b-col sm="2"> <b-dropdown :text="selectedItem" v-model="selectedItem"> <b-dropdo ...

Save the content of textarea within a .txt document while preserving the line breaks

I have a piece of code that successfully saves the value of a textarea into a local text file. However, I am facing an issue where I don't want to lose line breaks. Here is the code snippet and fiddle: HTML <textarea id="textbox">Type somethin ...

How do I access values in my factory after the deviceready event in AngularJS/Cordova?

I am currently utilizing the Cordova Device plugin to retrieve information about the device being used by the user. According to the documentation, it can only be invoked AFTER the deviceready function. Therefore, in my .run function, I have implemented th ...

What steps do I need to follow in order to properly execute this HTTP request?

Recently, I came across this amazing tool called SimplePush.io that is perfect for one of my projects. It works flawlessly via curl, as shown on their website: ~ $ curl 'https://api.simplepush.io/send/HuxgBB/Wow/So easy' or ~ $ curl --data &ap ...

The outcome of the Javascript Calculator is showing as "Undefined"

I've been attempting to create a calculator using JavaScript, but I'm facing an issue where the 'operate' function keeps returning Undefined, and I can't seem to figure out why. I suspect that the problem lies with the switch state ...

Vue enables components to be used in any part of the application, not limiting them to

Currently, I am initializing my Vue instance in the following manner: import ListClubsComponent from "./components/clubs/list-clubs.vue"; new Vue({ el: "#app", components: { "list-clubs": ListClubsComponent } }); It seems to be functi ...

The ultimate guide to removing a targeted form input using jquery

My HTML form contains two text inputs: <form id="insert_amount",onsubmit="submitAmount();return false;"> **input(type="text",placeholder="Your message",name="message")** **input(type="text",placeholder="Your amount",name="amount") ...

Opting for Mysql over MongoDB as the provider in Next.js with Next-auth

Exploring the Next.js framework for the first time, I've dived into using Next-auth to handle sign-up/login functionality based on the provided documentation. My experience so far has been smooth, especially with the MongoDB provider as recommended i ...