3
votes

I am working with Vuex and I am quite new to it. I am wanting to commit data to the store and replace replace the state with content of the payload.

My store is built using modules and the module in question is the user module,

Currently I am doing something like in my mutation,

setUser(state, payload) {
    state.user = {...payload.user}
}

This makes my state looks like this after a run a commit

user: {
   user: {
     nickname: 'Bob',
     host: true,
     emoji: 'Smile',
     passcode: 12345678,
     room_id: 123
   }
}

Ideally I don't want to have a user object in a user object, I either want each attribute of user to part of the state like,

state : {
    nickname: 'Bob',
    host: true,
    emoji: 'Smile',
    passcode: 12345678,
    room_id: 123
}

or it could look like this,

state : {
    user: {
        nickname: 'Bob',
        host: true,
        emoji: 'Smile',
        passcode: 12345678,
        room_id: 123
    }
}

I don't understand why I am getting state.user.user?

here is the user module of my state,

export default {
state: {
    user: {}
},
mutations: {
    setUser(state, payload) {
        state.user = {...payload.user}
    }
},
actions: {

},
getters: {

}

};

I have also tried the above with just state:{}

2
can you show me the output of console.log(payload) in the setUser(state, payload) methodisebarn

2 Answers

1
votes

This is because of you are indirectly creating another user object in the following mutation layer

   setUser(state, payload) {
        state.user = {...payload.user }
    }

In the mutation layer, state is already representing the entire user state. So you can directly assign the user object here.

   setUser(state, payload) {
        state = {...payload.user }
    }

Usually the state object need to initialize as follows,

state : {
    nickname: '',
    host: false,
    emoji: '',
    passcode: null,
    room_id: null
}
0
votes

I agree to @isebarn, if you provide what comes with your payload this should be solved quite easily.

{ "quiz_history": [], "user": { "id": 1, "nickname": "Bob", "login_code": "76752576", "host": 1, "room_id": 1, "emoji": "Smiley", "created_at": "2019-10-11 11:09:12", "updated_at": "2019-10-11 11:09:12" } }

If that's what you get and pass into the method, it should work. But I guess you maybe pass something else and the three dot spread syntax goes wrong.