To create a new record, I define the record object within the components data() function, and bind it to form fields using v-model. This object is then passed to a Vuex action that POSTs the new record to the back end, and then sends the object to the corresponding mutator.
The issue is, when changes are made to the original object defined in data(), those appear to cascade to the object that was pushed into the store.
I understand the pass by reference concept, but it seems this pattern should not be affected. Is there a better pattern to use when creating a new DB record?
Add Record Vue
<v-text-field
v-model="newRecord.name"
/>
...
export default {
data() {
return {
newRecord: {}
}
}
}
...
methods: {
addRecord(){
this.addRecordAction(this.newRecord)
...
this.newRecord.name = 'new name' // <== reflects in vuex store!
}
}
Vuex Record Store
async addRecordAction({commit}, newRecord){
const response = await axios.post('/api/record', newRecord)
newRecord = response.data // contains record's new ID
commit('addRecordMutation', newRecord)
}
...
addRecordMutation: (state, newRecord) => (state.records.push(newRecord))
Because your addRecordAction is asynchronous, this.newRecord.name = 'new name' is likely being executed prior to the addRecordAction, and thus because you passed by reference the object being added has the new name.
Easiest solution 'await' addRecordAction before setting the name.