Update two distinct object properties using a singular reference in Vue's set method

I'm facing an issue while trying to insert an object into an array using the Vue.set function. The problem is that it adds the item to a different object with the same array property. Here's a snippet of my code:

data() {
    return {
      ...
      form: {
        ...
        client_a: {
           ...
           items: []
        },
        client_b: {
           ...
           items: []
        },
      }
    };
  },

When I execute the following code (adding an item to client_a.items):

this.$set(this.form.client_a.items, 'key', { prop1: '', prop2: '' })

Unexpectedly, client_b.items also gets updated with the same value as client_a's items:

console.log(this.form.client_b.items)

The output is:

[
   'key': { prop1: '', prop2: '' }
]

Instead, the expected result for this.form.client_b.items should be an empty array, as nothing was added to it. Here is a link to the code example for reference: https://codesandbox.io/s/proud-fast-bjvyr

Answer №1

Pointing out by @skirtle is the fact that the base_client.functions property is the exact same array. A quick solution in the beforeMount() method:

beforeMount() {
  this.form.client_a = {
    ...this.base_client,
    functions: []
  }
  this.form.client_b = {
    ...this.base_client,
    functions: []
  }
  this.form.functions = [
    {
      key: "key-1",
      name: "Test"
    }
  ];
}

Although not the most elegant approach, it should get the job done. An alternative method would be to turn base_client into a function with a return value, creating a new returns array each time.

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

Maximizing the efficiency of Java Script code

I am struggling with optimizing this JavaScript code that adds and removes classes based on the presence of a specific class in the next rows of a table. Can anyone provide some guidance on how to make this code more efficient? $(".showTR").click(functi ...

Exploring the functionalities of class methods within an Angular export function

Is it possible to utilize a method from an exported function defined in a class file? export function MSALInstanceFactory(): IPublicClientApplication { return new PublicClientApplication({ auth: AzureService.getConfiguration(), <-------- Com ...

Issue with PHP Upload: Index is undefined

Having Trouble with PHP Upload: Encountered an issue: Undefined index: file in Error on line: $count = count($_FILES['file']['name']); Tried numerous codes to fix this error, but none have worked so far PHP Code: <?php $count ...

Why won't the CSS update in Next.js when the local state variable changes on page load?

I seem to be facing an issue with a variable stored in localStorage that changes when using a toggle button. The color changes correctly upon toggling the button, but upon page refresh, it doesn't display the correct color saved in local storage. Eve ...

Using GraphQL in React to access a specific field

Here is the code snippet I am working with: interface MutationProps { username: string; Mutation: any; } export const UseCustomMutation: React.FC<MutationProps> | any = (username: any, Mutation: DocumentNode ) => { const [functi ...

Uh oh! An error occurred when trying to submit the form, indicating that "quotesCollection is not defined" in Mongodb Atlas

Displayed below is my server.js file code, along with the error message displayed in the browser post clicking the Submit button. const express = require('express'); const bodyParser = require('body-parser'); const MongoClient = require ...

Why does Material-UI TableCell-root include a padding-right of 40px?

I'm intrigued by the reasoning behind this. I'm considering overriding it, but I want to ensure that I'm not undoing someone's hard work. .MuiTableCell-root { display: table-cell; padding: 14px 40px 14px 16px; font-size: 0. ...

Utilizing Vue.js to dynamically update an Amcharts4 chart

Currently, I am utilizing AmCharts4 in conjunction with Vue.JS. Initially, I have set up the default chart design to display when the page loads. However, upon attempting to add dynamic values post-page load (via a button click), the changes do not appear ...

Elevate your tooltips with Bootstrap 5: enabling hoverable tooltips and clickable links

At times, you may want to include clickable links in tooltips. I recently encountered this issue while using Bootstrap 5 and had trouble finding a solution. After some trial and error, I finally figured it out and wanted to share my findings. The standard ...

Guide to attaching and displaying an image on a Three.js map

Currently, I have a 3D map loaded with three.js that includes mouse interaction. I've managed to place an image on the map using absolute positioning, but unfortunately, as I move the map around, the image stays stationary. Does anyone know how I can ...

Unable to connect to server using local IP address

Currently utilizing a freezer application () and encountering an issue where I can only access the server on localhost. I attempted to modify the settings.js file by replacing 127.0.0.1 with 0.0.0.0, rebuilt it, but it still persists on localhost. Even aft ...

The code is not executing properly in the javascript function

Hello there! I've created a basic login form with JavaScript validation, but for some reason, the code below isn't functioning properly. Here is my HTML and JS code: <head> <script type="text/javascript"> function ha ...

Struggling to determine if the checkbox has been ticked?

I have integrated a like button on my website using socket io to ensure that it updates for all users when the like button is clicked. I have successfully implemented a like() function that emits liked, increments a counter, and displays it on the page. Ho ...

Tips for overlaying text onto a canvas background image

I'm curious about how to overlay text on top of an image that is within a canvas element. The image is a crucial part of my game (Breakout), so it must remain in the canvas. I've tried adding text, but it always ends up behind the image, which is ...

"By setting the HTML input box to read-only, the JavaScript button has the

Check out this js fiddle demonstration: http://jsfiddle.net/YD6PL/110/ Here is the HTML code snippet: <input type="text" value="a" readonly> <input type="text"> <input type="text"> <div> <button class="buttons">c</button ...

Parse a string in the format of "1-10" to extract the numbers and generate an array containing the sequence of numbers within the range

Looking to convert a string in the format "1-10" into an array containing the numbers within that range. Display the array on the screen using a for loop. For example, if "1-5" is provided, the resulting array should be: {1, 2, 3, 4, 5} Create a workflow ...

Identifying the presence of vertical scrolling

Is there a way to achieve the same functionality in JavaScript without using jQuery? I am looking to detect the visibility of the scrollbar. $(document).ready(function() { // Check if body height is higher than window height :) if ($("body").heigh ...

Troubiling Responsive Menu in React

I am currently working on developing a React Responsive Navigation with SCSS, but I am facing an issue. When I click on the hamburger button, nothing happens and the menu does not slide down in the mobile view. I tried inspecting the code in the browser to ...

Storing the Outcome of a mongodb Search in a Variable

I'm encountering an issue where the result of a MongoDB find operation is not being assigned to a variable (specifically, the line var user = db.collection("Users").findOne below), and instead remains undefined. I am aware that the find function retur ...

switching the image source by selecting different options from a dropdown menu and leveraging JavaScript

I have been attempting to change the src of an image using JavaScript's addEventListener, but for some reason it is not working. Here is an example to illustrate my issue: let bulbImage = $.querySelector(".bulb-image"); let turnOnOption = $.querySele ...