2

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

1 Answer 1

1

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
    },
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.