Why does adding to an array in the Vuex store replace all existing values with the last entry?

Utilizing vuex-typescript, here is an example of a single store module:

import { getStoreAccessors } from "vuex-typescript";
import Vue from "vue";
import store from "../../store";
import { ActionContext } from "vuex";

class State {
  history: Array<object>;
}

const state: State = {
  history: [],
};

export const history_ = {
  namespaced: true,
  getters: {

    history: (state: State) => {

      return state.history;
    },

  },
  mutations: {

    addToHistory (state: State, someob: any) {

      state.history.push(someob);

    },

    resetState: (s: State) => {
      const initial = state;
      Object.keys(initial).forEach(key => { s[key] = initial[key]; });
    },
  },

  actions: {
    addToHistory(context: ActionContext<State, any>, someob: any) {
      commitAddToHistory(store, someob);
    }

  }

const { commit, read, dispatch } =
  getStoreAccessors<State, any>("history_");
const mutations = history_.mutations;
const getters = history_.getters;
const actions = history_.actions;

export const commitResetState = commit(mutations.resetState);
export const commitAddToHistory = commit(mutations.addToHistory);
export const getHistory = read(getters.history);
export const dispatchAddToSearchHistory = dispatch(actions.addToHistory);

When using dispatchAddToSearchHistory or commitAddToHistory, all values in the store are consistently overwritten. For instance, after adding an element to the store:

store = [
  {
    a: 1
  }
]

If another object like {b: 2} is added, the store will then appear as:

store = [
  {
    b: 2
  },
  {
    b: 2
  }
]

This pattern continues where each successive entry overrides all previous ones. Adding {c: 3} results in the following store (and so forth):

store = [
  {
    c: 3
  },
  {
    c: 3
  },
  {
    c: 3
  }
]

Answer №1

It appears that you might be consistently sending the same object each time.

Consider implementing this mutation:

addToHistory (state: State, someObj: any) {
  state.history.push({...someObj});
}

Alternatively, you could try this action:

addToHistory(context: ActionContext<State, any>, someObj: any) {
  commitAddToHistory(store, {...someObj});
}

By using the spread operator like this, the object will be cloned, ensuring that each item added is a new object.

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

Can an array in html be accessed using a scope variable?

I am facing a challenge with utilizing a Json array in my template file. To access specific elements of the array, I need to use a scope variable. While I can achieve this in the controller, I also require the same functionality in the HTML file. An excer ...

Reload the page when the value reaches 1

Hello, I am currently working on creating a system where my index page refreshes when a value in my database is set to 1. However, I am having trouble with the code as only my index.php is not refreshing. index.php <script> interval_timer = setInt ...

Executing the slideToggle() function in JQuery with javascript

Trying to create a script that expands and collapses when users click on either the text or image. The image is a basic arrow that switches to an arrow pointing upwards when the div is expanded. The issue I'm facing is that the text disappears when t ...

The wait function does not pause execution until the element is found within the DOM

Upon clicking the Next button to proceed with my test, I encountered a transition on the page that prevented me from inputting the password. To solve this issue, I implemented the wait method to pause for 1 second until the element is located. The error ...

Unable to resolve the issue of Duplicate keys detected with value '0'. This could potentially lead to errors during updates

Encountered a warning in Vue js stating 'Duplicate keys detected: '0'. This warning could potentially lead to an update error. To resolve this issue, I utilized the getter and setter in the computed variable and dispatched the value to Vuex ...

Creating Comet applications without the need for IFrames

Currently embarking on my journey to develop an AJAX application with server side push. My choice of tools includes Grizzly Comet on Glassfish V2. While exploring sample applications, I've noticed that most utilize IFrames for content updates on the c ...

Loading external scripts prior to component loading in Vue.js

Within my Vue project, I have the need to fetch a script from a server location (e.g. https://myurl.com/API.js). This script contains a variable that I intend to utilize within my Vue component/view. The issue arises when I attempt to load this script usi ...

Find the name of the region in the user's query

I've implemented the weather-js npm module (weather-js) to retrieve weather information for a specific region. While everything is functioning correctly, I'm looking to customize it based on user input. The module currently only accepts region ...

The function addClass() seems to be malfunctioning

I'm currently experimenting with creating a scrolling cursor effect on a string of text. The goal is to make it look like the text has been highlighted with a blinking cursor, similar to what you see in your browser's search bar. window.setInter ...

update the value of a global variable within a jQuery function

Currently, I am facing an issue with a global variable in jQuery. Here is my code snippet: var namep = ''; $("#page2").bind('pageshow', function (event , data) { var perso = $(this).data("url").split("?")[1]; perso_name = perso. ...

Exploring the process of retrieving array elements from an AJAX response transmitted from PHP

Here is an example of jQuery code for an ajax function: $(document).ready(function() { $("#zip_code").keyup(function() { var el = $(this); var module_url = $('#module_url').val(); if (el.val().length === 5) { $.ajax({ ...

Altering the hover functionality for dynamically created class elements

I have a vision to create a unique e-commerce storefront with tile design, featuring an item thumbnail that reveals the item name upon hovering. I found inspiration from this example, but I want the item name to slide up smoothly on hover, rather than simp ...

Divide the division inside the box by clicking on it

I am looking to create a unique div with a random background color and a width of 100px. Additionally, I want to have a button that, when clicked, will split the original div into two equal parts, each with its own random background color. With each subs ...

Choosing multiple lists in Angular 2 can be achieved through a simple process

I am looking to create a functionality where, upon clicking on multiple lists, the color changes from grey to pink. Clicking again will revert the color back to grey. How can I achieve this using class binding? Below is the code snippet I have tried with ...

Managing loading and changing events using Angular, jQuery, and Web API

I am populating a dropdown select using ng-repeat. <select onchange="ChangeMonth()" id="month"> <option ng-repeat="(key,val) in Months" ng-selected="val==ActiveMonth" value="{{key}}"> {{val}} ...

The resizing of the window does not trigger any changes in the jQuery functions

Here is a snippet of jQuery code that executes one function when the window size is large (>=1024) and another when it is resized to be small. Although the console.logs behave as expected on resize, the functions themselves do not change. This means th ...

Can Ansible and Pulumi be integrated to work together effectively?

Is it possible to create multiple DigitalOcean droplets in a loop and then use Ansible to configure software and security measures on them, similar to how Terraform works? If so, what would the JavaScript/TypeScript code for this look like? I couldn' ...

Refresh WebPage automatically after a Servlet successfully uploads and processes an image

I have a webpage that includes an image and a button. When the button is clicked, it uploads the image by submitting a form to a file upload servlet. However, after successfully uploading the image, the servlet does not display it in the img tag. Here is ...

The creation and addition of Vue components dynamically has failed due to the inability to mount the component, as the template or render

After going through numerous Stackoverflow posts with similar symptoms, I found that none of the solutions solved my issue. According to this particular post, there are various reasons that could cause this problem. To troubleshoot, I upgraded all my npm, ...

Getting just the outer edges of intricate BufferGeometry in Three.js

Currently, I am immersed in a project that involves zone creation and collision detection using Three.js. The primary objective is for my application to effectively manage collisions and produce a BufferGeometry as the final output. My aim is to visually r ...