Home > OS >  VueX replace array data in state
VueX replace array data in state

Time:10-02

I am not sure how to explain this so lets give it a go. Just know I am JUST learning the potential of VueX so please bear with me.

I have a state object array called currentRoom Which should only hold one object at time. So by the name, this means that a user is inside a room, then they change rooms, so currentRoom should then change its data to the new room. Right now, all it does it add objects to itself growing larger and larger.

What is it I need to change to accomplish my goal?

export const actions = {
    [types.CURRENT_ROOM]({state, commit}, room) {
        commit(types.CURRENT_ROOM, {room});
    },
}

export const mutations = {
    [types.CURRENT_ROOM](state, {room}) {
        state.currentRoom.push(room)
    },
}

export const types = {
    CURRENT_ROOM: 'current_room'
}

CODE I AM USING INSIDE MY VUE FILE

this.$store.dispatch(RoomTypes.CURRENT_ROOM, room);

in my head I feel like there should be something like REPLACE instead of dispatch or maybe I am just thinking about this wrong. So educate and school me oh great people off Stack Overflow!

SIDE NOTE: Vue 3 and VueX 4

CodePudding user response:

The array grows because you're calling Array.prototype.push(), which appends an item to the array. Assuming a single-element array, you can replace the array element by using square brackets and 0 for the array index:

// store.js
export const mutations = {
    [types.CURRENT_ROOM](state, {room}) {
        state.currentRoom[0] = room
    },
}

However, arrays are intended to hold multiple values. If you only have one value, there's no need for an array.

state.currentRoom should be changed from an Array to an Object:

// store.js
export const state = () => ({
    currentRoom: {} // or null
})

And the mutation should assign the new value to state.currentRoom:

// store.js
export const mutations = {
    [types.CURRENT_ROOM](state, {room}) {
        state.currentRoom = room
    },
}
  • Related