I am encountering an issue with my Vuex store in a Vue2 and Vuex2 setup.
Upon dispatching a specific action, it alters the state of 2 elements in my store. Here's a snippet of the state with some dummy data for clarity:
{
"clients":[
{
"user":{
"id":7,
"name":"Luis",
"lastName":"Cervantes",
- rest of user data -
},
"addresses":[
{
"id":5,
- address data -
},
{
"id":3,
- address data -
}
]
},
{
"user":{
"id":8,
"name":"Richard",
"lastName":"Czyrny",
- rest of user data -
},
"addresses":[
{
"id":4,
- address data -
}
]
}
],
"client":{
"user":{
"id":7,
"name":"Luis",
"lastName":"Cervantes",
- rest of user data -
},
"addresses":[
{
"id":5,
- address data -
},
{
"id":3,
- address data -
}
]
},
}
Within the state, there is a clients array.
Additionally, there is a client object that holds the currently selected client. Actions are in place to alter the client user and addresses objects separately.
Actions
SET_CLIENT_PROFILE_USER: ({commit, state}, user) => {
commit('CLIENT_PROFILE_USER', user)
},
SET_CLIENT_PROFILE_ADDRESSES: ({commit, state}, addresses) => {
commit('CLIENT_PROFILE_ADDRESSES', addresses)
}
Mutations
'CLIENT_PROFILE_USER': (state, user) => {
state.client.user = user
},
'CLIENT_PROFILE_ADDRESSES': (state, addresses) => {
state.client.addresses = addresses
}
Here are some computed properties used within a component:
clientsList(){
return this.$store.getters.getClients
},
client(){
return this.clientsList[this.client_index]
},
- more computed properties -
And here are some watchers that trigger the action dispatch:
watch: {
'client_index': function (val, oldVal) {
var c = this.client;
this.$store.dispatch('SET_CLIENT_PROFILE', c);
this.address_index = '';
},
'address_index': function(val, oldVal){
- logic for dispatching action -
}
},
It seems that when SET_CLIENT_PROFILE_ADDRESSES is dispatched, it inadvertently modifies the addresses in both client.addresses and the corresponding clients object related to that address, instead of just changing the client.addresses part.
I am struggling to pinpoint the root cause of this behavior and am seeking a solution to only alter client.adresses.