简体   繁体   中英

Vuex Mutation Not Setting State Correctly

I am working on a Vue/Vuex project and just ran into a very odd issue. I have a mutation where I am console logging before and after mutating the state to the payload and it shows an array of two objects. However, the state only shows the first object in the array. Here is my mutation:

mutations: {
  SET_LOADED_BUILDINGS (state, payload) {
    console.log(payload)
    state.buildings = payload
    console.log(state.buildings)
  }
}

The console.log(payload) outputs an array of two objects (what I want/expect) and the console.log(state.buildings) also outputs the same array of two objects. However, in the Vue Dev Tools, it only shows one object (the first one) in the array.

The reason it was only displaying one object in the payload but two in the console.log is because of an asynchronous issue. I was using Array.push to push all the objects into the array and was pushing the payload before it completed. I implemented a promise and used Promise.all to ensure that the Array.push finished before setting the state to the payload.

Just a quick reminder, actions CAN be async, mutations CAN'T be async. Theres a logic behind this reasoning, mutations are the "end" point of your data mutation the log trace capture before and after data has been changed you can get in the scenario (like this) where you commit before the data is ready. See: Mutations must be synchronous

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM