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

Creating a Vue.js component that animates text to fade in and out within a textarea when a button

I need assistance with updating a <textarea> element in my Vue application. Currently, I have the textarea bound to some data in my state. However, when a button is clicked, I want the existing data in the textarea to fade out and be replaced with ne ...

A JavaScript pop-up box with two windows

Struggling to create two separate dialog boxes using this code. The issue is that when I add the code for the second dialog box, it only appears if the first one does too. Here's the code for the first dialog: function showPopUp(el) { var ...

What is the best way to incorporate component-specific CSS styles in React?

This is the layout that I am attempting to replicate (originally from react-boilerplate): component |Footer |style.css |Footer.js In Footer.js, the styles are imported in a very elegant manner like this: import React from 'react'; im ...

When accessing a page from a link, JavaScript sometimes does not immediately execute on the first attempt

I'm encountering a strange issue in my rails application, where a template fails to execute the Javascript code the first time it is loaded via a link on my home page. This problem only occurs when accessed through the link for the first time. I' ...

The declaration file for the 'react' module could not be located

I was exploring Microsoft's guide on TypeScript combined with React and Redux. After executing the command: npm install -S redux react-redux @types/react-redux I encountered an error when running npm run start: Type error: Could not find a decla ...

Is there a way to stop TD from going to the next line?

I am using Javascript to dynamically generate a table and I want it to extend beyond the boundaries of the page. When I manually create the table, it works fine and extends off the page, but once I put it into a loop, the <td> elements wrap onto a se ...

Guide to executing two child processes sequentially in Node JS

I am working on two processes within a function: one generates a JSON file from an audio while the other normalizes the generated JSON file. However, I'm facing an issue where only one of the processes runs at a time - when the first one runs, the se ...

What is the process for obtaining the URL of the website that is hosting my iframe?

Do you have a technical inquiry? I am curious to know if it is feasible to retrieve the URL of the website that is hosting my iframe. The pages that host my iframe are utilizing the following code: <iframe id="vacancy-iframe" src="http://mypage.co ...

Dynamic manipulation of classes based on user attributes

One thing I've noticed is that certain WordPress themes, like 'Thematic', include user-specific classes in the body element to avoid using CSS browser hacks. For example: wordpress y2010 m02 d26 h05 home singular slug-home page pageid-94 pa ...

document ready function in the Microsoft AJAX client side library

The Microsoft AJAX client-side library contains various functions that imitate the server-side Page Life Cycle and conditions like if (!Page.IsPostBack). I am unsure about which client-side function corresponds to the equivalent server-side method. What is ...

Choosing the right framework for implementing push notifications can be a critical decision. Should

I am currently working on a Java application that requires the server to send push notifications to the client every one second. To achieve this, I am using HTML5 server-sent events for one-way communication from the server to the client. However, my conce ...

What is the method for setting the content-type in an AJAX request for Android browsers?

I am facing an issue with my ajax call to the Rails server. The response from the server varies between HTML and JSON based on the content type. Surprisingly, this works smoothly on iPhone and desktop browsers like Chrome, but I am encountering a problem o ...

Is there a way to retrieve a different value within the JavaScript code (imagepicker)?

I need help with setting up a page where users can choose an image to forward them to another page. However, I'm facing an issue when the user chooses two images at once. Can anyone provide ideas on how to handle forwarding in this scenario? You can c ...

Utilize AJAX to connect to a remote domain from an extension

I am currently working on creating a Chrome extension that will utilize AJAX to fetch data from a specific webpage and then generate notifications based on the content of that page. The webpage I am targeting is a ticketing system, and my goal is to deter ...

Tips for ensuring session token verification remains intact upon reloading

I am currently in the process of developing a website using the Next.js framework and I am seeking advice on how to prevent the reload effect that occurs when transitioning from the login page back to the main page for just a fraction of a second. Below i ...

Grid layout with card tiles similar to Google Plus

I'm looking to develop a scrolling grid with card tiles similar to Google Plus that has three columns. I am currently using Material UI, but I can't seem to find the right functionality for this. I have experimented with the standard Material UI ...

Retrieving the input value using ref in Vue 3 and TypeScript

It appears to be a straightforward issue, but I haven't been able to find consistent Vue 3 TypeScript documentation on accessing an input field and retrieving its value from within a function. <template> <Field type="text" ...

There was an error: "Uncaught TypeError - onPageChange function is not defined for the DataGrid component in Material

I'm struggling to integrate a DataGrid component into my application. While the table renders correctly with the code provided, I encounter an error when clicking on the next page icon - react-dom.development.js:327 Uncaught TypeError: onPageChange is ...

When implementing AngularJS in a situation where the page layout is created by the user, what is the best

As I work on developing a web application, my main goal is to incorporate around 6 unique "widgets" that users can interact with. These widgets will serve different functions and users will have the ability to add, remove, and position them as they wish on ...

Unable to render properly after saving to Firebase

Currently, I am working on developing an express app that creates a Google map using geo coordinates extracted from photos. My goal is to utilize Firebase for storing data related to the images. While my code is functioning properly, I encountered an issue ...