Is it possible that when a new item is added to an array of a reactive object, all existing items are replaced in the array

It seems that the issue lies within the title. I suspect that the ref() and reactive() functions are conflicting with each other somehow, but I am unsure of how to address it.

Below is the snippet of the component utilizing the store:

<script setup>
    import { ref } from "vue";
    import { store } from "@/store.js";

    const game = ref({
        date: null,
        location: null,
        length: null,
    });
</script>

<template>
    <form @submit.prevent="store.addGame(game)">
        <input v-model="game.date" type="date" required />
        <input v-model="game.location" type="text" placeholder="Location" required />
        <input v-model="game.length" type="number" placeholder="Length (in minutes)" required />
        <button class="button" type="submit">Submit ✔</button>
    </form>
</template>

The issue arises in the store file, specifically in the games array, after adding multiple items...

Below is the content of store.js:

import { reactive } from "vue";

export const store = reactive({
    games: [],

    addGame(game) {
        this.games.push(game);
        console.log(this.games);
    }
});

Answer №1

The issue arises because the objects you insert into the games array all point to the same reference. To resolve this, make a modification in the store.js

import { reactive } from "vue";

export const store = reactive({
    games: [],

    addGame(game) {
        this.games.push({...game}); // updated line
        console.log(this.games);
    }
});

Answer №2

Don't just "replace", every mention of game refers to the same reactive variable defined in const game = ref().

When you use store.addGame(game), you are adding the exact same game to the store. Because game is reactive, it automatically reflects the latest input value through v-model.

If you add another button to verify the value in the store, change the input value, and then click the Test button, you'll notice that store.games also gets updated.

<template>
    <form @submit.prevent="store.addGame(game)">
        <input v-model="game.date" type="date" required />
        <input v-model="game.location" type="text" placeholder="Location" required />
        <input v-model="game.length" type="number" placeholder="Length (in minutes)" required />
        <button class="button" type="submit">Submit ✔</button>
    </form>
    <button @click="console.log(store.games)">Test</button>
</template>

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

I'm at a standstill with the onclick function, even after searching on Google I couldn't

I've been struggling to make this work and have tried everything I found on Google, but I'm still stuck. What I'm trying to achieve is loading the value of (div id="availablecredits") into (div id="beta") when clicked. Can anyone help me wit ...

Once the final row in the table is removed, the width of the second cell in the top row will be set to 0

Can anyone help with an issue I'm having on my website? I created a basic web page with some Javascript that allows for inserting and deleting table rows. However, I've noticed that in IE6, when I delete the last inserted row, the second cell of ...

Tips for creating a typescript typeguard function for function types

export const isFunction = (obj: unknown): obj is Function => obj instanceof Function; export const isString = (obj: unknown): obj is string => Object.prototype.toString.call(obj) === "[object String]"; I need to create an isFunction method ...

What is the best way to transform a database object into a complex JSON structure?

My goal is to retrieve a specific person from a list of persons. The POST method works correctly and I am able to obtain the desired person as "chosenPerson" in the controller. However, when I try to convert this person into a complex JSON object using ser ...

What is causing a single state update when setState is called twice in React?

It seems like I'm making a beginner mistake in React as I am trying to call the "addMessage" function twice within the "add2Messages" function, but it only registers once. I believe this issue might be related to how hooks work in React. How can I mod ...

Retrieving data from an array using an AJAX request function

I've been attempting to utilize an AJAX call to update a series of image elements on a webpage. The array containing the elements to update is populated with URLs fetched from a PHP page via AJAX. The issue I'm encountering with the code provide ...

Oops! You can only have one parent element in JSX expressions

I'm working on creating a password input box, but I keep encountering an error when integrating it into my JS code. Here's the snippet of my code that includes TailwindCSS: function HomePage() { return ( <div> <p className=&q ...

show the array as an image using the mean stack technology, which includes node.js and Angular

My persona has an attribute retrieved from MongoDB known as "faceDetection.photo", which is an array of values. Here is a snippet of the code: persona.faceDetection.photo=[255,216,255,224,0,16,74,70,73,70,0,1,1,1,0,1....etc] var encodedData = window.btoa( ...

What are the steps for converting a structured text document into a SQL table?

I am currently working on a project that involves the need to save and load a structured text document, similar to MS Word, into/from a MySQL table. For instance, if given a sample document like sample.doc, the goal is to save both the content and formatt ...

Why won't my AngularJS Google Maps marker trigger any events?

My issue is with the marker event not working on a UI Google Map. I am using this link. Here is my view setup: <ui-gmap-markers models="mapResult" fit="true" idkey="mapResult.id" coords="'form_geo'" click="'onclick'" events="mapRe ...

Ways to automatically include a local variable in all functions

In each of my functions, I start with this specific line: var local = {} By doing so, it allows me to organize my variables using the following structure: local.x = 1 local.y = 2 Is there a way to modify all function prototypes to automatically include ...

What is the best way to retrieve values from a nested mongodb object?

I am currently working with a Company mongodb structure that looks like this: { "companyName" : "SomeCompany", "Products" : [ { "productId" : "e3rQACssGkfp9zsue", "productCode" : "271102502", "memberPrice" : " ...

Deleting a model from an array using Angular

I am working on a component that has a list of posts, and I retrieve them using the following code snippet: export class PostsComponent implements OnInit { posts; constructor(private http: Http) { } ngOnInit(): void() { this.http ...

The JSP page does not redirect after an Ajax post request has been made

When submitting a form with basic AJAX post, I am facing an issue where the redirection to the JSP does not occur upon success. Setting the redirect programmatically seems to create a new JSP instead of utilizing the existing one with POST data. After debu ...

Even though the script from the specified URL was loaded successfully, it was identified as having an invalid MIME type ("text/html") for JavaScript

I am using a Flask backend and here is my webpack configuration (excluding sass/css/babel). const webpack = require('webpack'); const resolve = require('path').resolve; const HtmlWebpackPlugin = require('html-webpack-plugin') ...

Display the input once the button is pressed

On my home page, I need to hide the <input> element until the button is clicked. When designing my typing game for mobile users, I included an input field that should only be visible upon clicking the button. ...

Create a new URL using `window.URL.createObjectURL` and specify the filename to open the PDF

Is there a way to customize the filename in createObjectURL of the blob? Currently, it generates a URL like this: <URL>/bfefe410-8d9c-4883-86c5-d76c50a24a1d const data = window.URL.createObjectURL(newBlob); const pdfWindow = window.open(); pdfWindo ...

Show the tinymce textbox dynamically

Whenever I select an option from a drop-down list, a set of elements are dynamically inserted into a form on the DOM using ajax. Among these elements are textareas that I want to convert into TinyMCE textareas. In my HTML head section, I have the followin ...

How can I access the post-AJAX version of the browser using Zombie.js pressButton?

Utilizing zombie.js for automated testing of browser actions involves simulating clicking on a button to submit a form. However, in the real browser environment, this action triggers an AJAX request that dynamically adds two div.alert elements to the docum ...

I have incorporated jquery-1.2.6.js into my project but I am encountering difficulties utilizing the live method

C# foreach (DataRow Row in oDs.Tables[0].Rows) { LitPreferances.Text += "<Li ID=LI_" + Row["pk_Preference_Branch_ID"].ToString() +"_"+ Row["pk_Preference_BranchType_ID"].ToString() +">" + Row["Branch_Name"].ToString() + "&nbsp;&nbsp;< ...