Vue(x) causing state mutation in array

I'm currently in the process of building a Vue application to help me learn more about web development. I've hit a roadblock when it comes to updating an array in my state with data from an API. Here's a snippet of the API response:

{
  "stations": [
    {
      "id": 1,
      "name": "Station 1",
    },
    {
      "id": 2,
      "name": "Station 2",
    }
  ]
}

Here is the action defined in my Vuex store (the ApiService is responsible for returning the axios response):

actions: {
  fetchStations({ commit }) {
    let promise = ApiService.getStations()
    promise.then(res => {
      console.log(res.data)
      commit('SET_STATIONS', res.data)
    })
  },

And here is the mutation:

mutations: {
  SET_STATIONS(state, stations) {
    state.stations = stations
  },

After logging the res.data in the developer tools, I noticed that the id of both objects is '2' even though they are different in the database.

Interestingly, if I comment out the commit line in my action like this:

actions: {
  fetchStations({ commit }) {
    let promise = ApiService.getStations()
    promise.then(res => {
      console.log(res.data)
      // commit('SET_STATIONS', res.data)
    })
},

The issue disappears and res.data appears to be completely different.

Could someone explain why this happens and provide insight on how I could resolve it?

Thank you!

Answer №1

Due to the utilization of the stations data in a specific location, it appears that you may be employing something along the lines of

v-for"item in stations" :key="item.id"
. By executing commit('SET_STATIONS', res.data), this modifies the stations array and leads to duplicate id occurrences.

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

Enrollment in the course is conditional on two words being a perfect match

I have a concept in mind, but I'm struggling to piece it together. I have bits of different methods that just don't seem to align. That's why I'm reaching out for your expertise. Let's say I have 3 content containers with the clas ...

Making if-else statements easier

Greetings! I have a JSON data that looks like this: { "details": { "data1": { "monthToDate":1000, "firstLastMonth":"December", "firstLa ...

Issues arise with AngularJS showing images fetched from an API

Currently, I am facing an issue where I am trying to display images from a REST API but keep receiving a "error 403" message. Here is the link to my JSFiddle. Please take a look, as I have attempted using both <img src=""> and ng-src='', bu ...

The unhandled type error rises with each scroll I make

Having been diligently working on my current website project, I encountered a puzzling issue. Upon writing code to implement smooth scrolling throughout the site, I found myself facing a persistent error that continues to escalate with each scroll up or do ...

What is the best way to display images when a single element in a list created by ngFor is hovered over in Angular 2

displayStar(val) { this.starDisplayed = true; } <ul class="listboxtickets"> <li class="selectlistticket" *ngFor="let item of ticketList" (mouseover)="displayStar(item.id)" (mouseleave)="hideStars()"> <div class="ticket ...

Monitoring the flow of data between Angular JS resources and the promise responses

In my application, there is a grid consisting of cells where users can drag and drop images. Whenever an image is dropped onto a cell, a $resource action call is triggered to update the app. My goal is to display a loader in each cell while the update cal ...

Stock Chart that resembles the functionality of Google's popular line chart feature

Can anyone recommend a Javascript or SVG chart library that has a style similar to a Google Chart? I have been searching without much luck and would appreciate some guidance on how to achieve a similar look. I've looked into the Google Visualization ...

Utilize load-grunt-configs and run bower.install() with grunt

I have been attempting to break down my current Gruntfile into smaller parts for better clarity. However, I have encountered a hurdle while using bower.install to manage project dependencies. My directory structure appears as follows: package.json bower.j ...

NodeJS reports an invalid key length, while C# accepts the key length as valid

Currently, I am in the process of converting Rijndael decryption from C# to NodeJS. The Key (or Passphrase) being used is 13 characters long, while the IV used is 17 characters long. Note: The length choice for both Key and IV is beyond my control Disp ...

Is there a way to create a "navigate to" button directly from the text within a <p> element?

Within my HTML, there is a <p> tag which dynamically receives a link value from a JavaScript function. The link could be anything from www.google.com to youtube or instagram. How can I utilize the "copytoclipboard" library to copy this link to clipbo ...

The Child component is unable to render initially due to the Context API being undefined during the first render of the Child component

I'm struggling to ensure that a child component only renders when the Context API state I've set up is fully mounted. The Parent component fetches data from the server and sets the state based on the received information. Initially, I keep gettin ...

[VUE Warning]: The custom element <navigation-drawer> is not recognized - have you properly registered the component?

After importing two components from a custom library, I encountered an issue. When I run "npm run serve", no errors appear in the command prompt. However, upon opening localhost, all I see is a white screen and the console displays the following error mess ...

Having trouble with loading JSON due to a Cross-Domain AJAX problem

I am facing a challenge with a URL that I do not have control over, which returns a JSON string. Within this JSON string, there is a URL that I am attempting to load using JavaScript/jQuery AJAX. However, I am encountering a Cross-Domain issue while trying ...

What is the best way to invoke a function that is saved in an array of options while using setTimeout() within an AJAX callback?

Below is the pertinent code snippet: success: [ setTimeout(function () { ajax.success }, 250), //... An interesting observation I made is that I am able to invoke ajax.success from inside the success ...

Animation does not occur after the stop() function is executed

My goal is to create a functionality where, upon moving back to the grey content box after leaving the button, the slideUp animation stops and the content slides down again. This works seamlessly with jQuery 1.x (edge), but when I switch to jQuery 1.10, th ...

Ways to resolve the error message "Type 'Promise<{}>' is missing certain properties from type 'Observable<any>'" in Angular

Check out this code snippet: const reportModules = [ { url: '', params: { to: format(TODAY, DATE_FORMAT).toString(), from: format(TODAY, DATE_FORMAT).toString() } }, { url: 'application1', params: { to: for ...

Nuxt is unable to modify the data variable

When working with Vue in Nuxt, I often encounter an issue where changes to a variable in the data section of my component do not reflect in the HTML. For example: export default { data () { return { openPopup: '1' } }, methods: ...

What causes the 'find' query to return a Query object instead of the expected data in MongoDB?

After researching extensively on SO, I have yet to find a solution to my ongoing issue. Currently, I am in the process of developing a project using node, express, and mongodb. To start off, I created a seeder file to populate some data into mongodb: var ...

I aim to prevent users from liking a post multiple times within Firebase

I came up with this code snippet to implement the Like functionality: /*Incrementing by 1 every time a user submits a like*/ db.collection("post").doc(postId).update({ likes: increment }) /*Collecting the UID of the user who submitted the l ...

Importing pixi-sound in the right way for PIXI JS

I have a question regarding the proper way to import pixi-sound into my project. I am facing an issue with the following code snippet: import * as PIXI from "pixi.js"; import PIXI_SOUND from "pixi-sound"; const EFFECT_SOUNDS = [...list of music] for (le ...