0
votes

I'm building a Vue application for learning purposes and I'm currently stuck on updating an array in my state with data from an API. This is my API:

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

This is the action in my Vuex store (the ApiService simply returns the axios response):

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

and this is the mutation:

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

When I check the logged res.data in the devtools I get this
As you can see the id of both Objects is '2' even though in the DB they are different.

Interestingly, when I comment out the commit line in my action like so:

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

the issue is gone and res.data is completely different

Can anyone explain to me why this is the case and how I could fix it?

Thank you!

1
can you please share your code ?Ahmad Noor
Remember that console.log prints live objects. I guess you are changing stations from different part of code (which depends on what is set by your mutation) Try to call commit('SET_STATION', ) directly with mock data and without and looks what happen.Vue dev tools extension should also help you to see when data in store is changed during time.farincz
I created a github repo with the full code: github.com/david-breidert/station-problemD. Breidert
Looks everything fine to me, It's probably something on a backend.DedaDev

1 Answers

0
votes

Because stations data was using in somewhere. I think you are using something like v-for"item in stations" :key="item.id". When you commit('SET_STATIONS', res.data), it changed stations. And it have duplicate id.