V-model is updating unreferenced state data - vue.js

I am trying to copy an object in the vuex store to a local component object so that I can change it locally and not modify the store state object. However, when I associate the local object with a textarea v-model, it changes the store state data even though it is not directly referenced. I am not sure how this is happening or even possible.
<v-textarea v-model="currentObj.poltxt" solo light></v-textarea>
watch: { //watch for current UID changes
"$store.state.currentUID"(nv) {
//Clearing the local temporary object
this.currentObj = {};
//Moving the store state data into the local object
this.currentObj = this.$store.state.docuMaster[this.$store.state.currentUID];
}
}
The watch function is executing and when I console log this.$store.state.docuMaster[this.$store.state.currentUID] I can see that v-model is directly updating it even though its referencing currentObj. Any idea why this is happening? The text box is not referencing the store in any other place in code.

If this.$store.state.docuMaster[this.$store.state.currentUID] is not a nested object then try using
//Moving the store state data into the local object
this.currentObj = Object.assign({}, this.$store.state.docuMaster[this.$store.state.currentUID]);
If this.$store.state.docuMaster[this.$store.state.currentUID]) is a nested object then you got to do deep clone
this.currentObj = JSON.parse(JSON.stringify(this.$store.state.docuMaster[this.$store.state.currentUID]));
Note:
Nested object in the sense I mean
docuMaster: {
UID: {
...
xyz: {}
},
....
}
Not a nested obj means
docuMaster: {
UID: {
//no inner objects
},
....
}

Related

vue unexpected reactivity from props

I just noticed an unexpected behaviour and now I don't know if it is normal or not.
I have a component named follows and a child component named follow-list-modal
I'm passing a followList (pagination ) from follows to its child component follow-list-modal
In the follow-list-modal I store the paginated array in the variable members
Follows.vue
<template>
<div>
<follow-list-modal
:follow-list="dataset">
</follow-list-modal>
</div>
</template>
<script>
export default {
props: {
dataset: {
type: Object,
default: {},
},
},
}
</script>
FollowListModal.vue
<template>
<div>
<button #click="fetchMore"> More </button>
</div>
</template>
<script>
export default {
props: {
followList: {
type: Object,
default: {},
},
data() {
return {
members: this.followList.data,
dataset: this.followList,
};
},
methods: {
fetchMore() {
let nextPage = parseInt(this.dataset.current_page) + 1;
axios
.get(this.dataset.path + '?page=' + nextPage)
.then(({ data }) => this.refresh(data))
.catch((error) => console.log(error));
}
},
refresh(paginatedCollection) {
this.dataset = paginatedCollection;
this.members = this.members.concat(...paginatedCollection.data);
},
}
When I click the button More in the follow-list-modal to get more data, I then want to append the new data to the members array.
The unexpected behaviour ( for me at least ). is that if I use push in the refresh method
this.members.push(..paginatedCollection.data);
It appends data not only to members but also to followList which is data that comes from the parent component follows
But if I use concat instead of push, it appends data only to members variable and not to followList
this.members = this.members.concat(..paginatedCollection.data);
Is this behaviour normal ?
I don't get why the followList changes when the members variable changes, I thought that reactivity is one way.
In other words, the members changes when the followList changes, but not the other way around
P.S I don't emit any events from follow-list-modal to follows or change the data of the follows component in any way from the follow-list-modal
In JavaScript, the properties of an Object that are also Objects themselves, are passed by reference, and not by value. Or you might say that they are shallow copied.
Thus, in your example, this.members and this.followList.data are pointing to the same variable in memory.
So, if you mutate this.members, it will mutate this.followList.data as well.
You could avoid this by doing a deep copy of the objects. The easiest method, and arguably the fastest, would be to use JSON.parse(JSON.stringify(obj)), but look at this answer for more examples.
data() {
return {
members: [],
dataset: [],
};
},
created() {
this.members = JSON.parse(JSON.stringify(this.followList.data));
this.dataset = JSON.parse(JSON.stringify(this.followList));
}
You instantiate your data with a direct link to the (initially undefined) property of your prop. This property is a complex entity like an Object (Arrays are Objects), and is thus called via reference. Since members references the same thing in memory as followList.data, when you're calling members, it will follow the reference to the same entity as followList.data. This doesn't have to do with Vue2 reactivity, but here's a link nontheless.
push mutates the array it is called on; it will follow the reference through members and change followList.data, updating its value when called through followList as well. Because the data key is not present on instantiation of the component, Vue can't watch it (just like you need to use Vue.set when adding a new key to a data object).
concat returns a new array of merged elements, and then replaces
the reference in members with the new array. Therefore from this point on you'll
no longer mutate followList.data, even with a push, as the reference has changed to a new entity.
When trying to set your initial members and dataset, I suggest using an initialization method that creates a clone of your followList and writes that to dataset, and running this on the created() or mounted() hook of your component lifecycle. Then create a computed property for members, no need to store followList.data thrice and potentially have dataset and members diverge.

Vuejs - add property to each item in an array with reactivity

I have banged my head against all kinds of walls for days and would love some help with this please.
I am getting the following error but can't really see how what I'm doing has anything to do with vuex here:
[vuex] do not mutate vuex store state outside mutation handlers.
In my vue component I define an empty array for future data I get from an external API.
data() {
return {
costCentres: [],
};
},
I have a watch on my vuex store object named schedule (which I've brought in using MapState... and also tried with a getter using MapGetter to see if that made any difference). In this watch I create my array costCentres, with each element consisting of about five properties from the API. I add two properties at this point (sections and tasks) which I intend to later populate, and which I need to be reactive so I do so in accordance with the Vue reactivity documentation which all the other questions I've found remotely like mine seem to reference.
watch: {
schedule() {
if (this.schedule.rows) {
this.costCentres = this.schedule.rows.filter((row) => {
return row.cells[
this.schedule.columnKeysByName["Cost Code"]
].value; // returns row if Cost Code value exists
});
this.costCentres.forEach((costCentre) => {
this.$set(costCentre, 'section', null);
this.$set(costCentre, 'task', null);
});
}
},
The this.$set lines throw the earlier mentioned error for every element in the array.
When I later update the properties, the change is reactive so its just the flood of error messages that's got me beat. Obviously if I don't use set then I don't get reactivity.
I have no idea how what I am doing is related to the vuex store as costCentre is a plain old data property.
I've tried hundreds of variations to get this all work (including this.someObject = Object.assign({}, this.someObject, { a: 1, b: 2 }) which doesn't seem to work) and I've run out of options so any assistance would be greatly appreciated!
(Please also let me know if I need to show more code - I was trying to keep this concise!)
this.schedule.rows is an array containing some objects (mapped from Vuex so the array and objects inside "belongs" to Vuex)
You are creating this.costCentres by filter - so in the end this.costCentres is just another array containing subset of objects from this.schedule.rows (elements inside are just pointers to objects inside Vuex)
In the forEach loop, you are modifying objects which are part of the Vuex store and as a result getting error [vuex] do not mutate vuex store state outside mutation handlers.
If you want to modify those objects, only way is to use Vuex mutations
Alternative solution is to make a copy of objects (create new objects with same values):
this.costCentres = this.schedule.rows.filter((row) => {
return row.cells[this.schedule.columnKeysByName["Cost Code"]].value;
})
.map((row) => ({...row, section: null, task: null }))
Note: code above creates just a shallow copy so if your objects does contain some deeply nested properties, you have to use some other way to clone them
Now objects inside this.costCentres are not part of the Vuex and can be modified freely without using mutations...

How do I make a state getter reactive when a dispatched action sets a state object with Vue.set?

I have a button that’s set to update the a store object using Vue.set but the getter for that same piece of data in a different component isn’t reactive until I change the state using a different component method.
The state object in question is set up as a hash that's keyed by UUID's. The object is generated and then added to the state object with Vue.set
The button is set to dispatch an action, which I see it going through immedietely in the devtool, that does this:
mutations: {
COMPLETE_STEP(state, uuid) {
let chat = state.chatStates[uuid];
let step = chat.currentStep;
Vue.set(chat.data[step], "complete", true);
}
},
actions: {
completeStep({ commit }, uuid) {
commit("COMPLETE_STEP", uuid);
}
},
Now, when I want to grab that data, I have a getter that grabs that data. This doesn't run until I do something else that causes a re-render:
getters: {
getChatStepComplete: state => (uuid, step) => {
let chatState = state.chatStates[uuid];
return chatState.data[step].complete;
},
}
I want the getter to show the updated change right away instead of waiting to update on a different re-render. How do I make that happen?
Figured out my issue: I wasn’t creating the data array when I first create and add chat to the state. Once I started initializing it to an empty array, it’s started being reactive.

UI not updating when nested array property value deleted, only when added

I have a page where an object with nested array values are passed in from the parent component. The user can then, using a series of events and components manage the data in these subscriptions. Currently I'm facing an issue where when a subscriptionId is removed from the props, conditions on the page aren't changing, but they do when it's added.
Child Component
export default {
props: {
// Format of this object is:
// { "gameId": [
// 'subscriptionId',
// 'subscriptionId',
// ] }
subscriptions: {
type: Object,
required: true
}
},
watch: {
subscriptions: {
handler: function (newSubscriptions, oldSubscriptions) {
// NEVER gets fired when `subscriptionId` deleted from array list, but is fired when a new subscription is added
console.log('handler');
}
},
deep: true
}
},
I suspect this might be related to how I'm removing the array from the object. Essentially I'm copying the array, deleting the index in question and overwriting the original array. My hope with this approach is that the watcher wouldn't be needed but it appears to have no impact. Here's the code that exists on the parent component to update the subscriptions:
Parent Component
// Works great, don't have any issues here
handleSubscribed (subscriptionId) {
let newSubscriptions = [subscriptionId];
if (this.subscriptions.hasOwnProperty(this.currentGame.id)) {
newSubscriptions = this.subscriptions[this.currentGame.id];
newSubscriptions.push(subscriptionId);
}
this.$set(this.subscriptions, this.currentGame.id, newSubscriptions);
},
handleUnsubscribed (subscriptionId) {
// if there's more than one, delete only the one we're looking for
if (this.subscriptions.hasOwnProperty(this.currentGame.id) && this.subscriptions[this.currentGame.id].length > 1) {
let newSubscriptions = this.subscriptions[this.currentGame.id];
delete newSubscriptions[newChannels.indexOf(subscriptionId)];
this.$set(this.subscriptions, this.currentGame.id, newSubscriptions);
// shows my subscription has been removed, but GUI doesn't reflect the change
console.log('remove-game', newSubscriptions);
return;
}
this.$delete(this.subscriptions, this.currentGame.id);
},
I was hoping watch might be the solution, but it's not. I've looked over the reactive docs several times and don't see a reason for why this wouldn't work.
VueJS version: 2.5.7
Use Vue.delete instead of the delete keyword.
The object is no longer observable when using delete, therefore not reactive.
Delete a property on an object. If the object is reactive, ensure the deletion triggers view updates. This is primarily used to get around the limitation that Vue cannot detect property deletions, but you should rarely need to use it.

Vue: How to iteratively update properties in props the correct way

I'm creating a component that updates props with values from local storage. The props are objects with multiple boolean properties (e.g. this.globalStates.repeat = false). Because I have more than one prop to update, I've created a method for any prop provided as an argument:
mounted(){
this.loadLocalData(this.globalStates, "states")
this.loadLocalData(this.globalSettings, "settings")
},
methods: {
loadLocalData(object, localVariable){ // 'object' receives a prop, 'localVariable' must refer to a string in localStorage (localStorage stores strings only).
const loadedObject = JSON.parse(localStorage.getItem(localVariable)) // Turn localStorage string into JSON object
if (loadedObject && typeof loadedObject === "object"){
for (let item in object){ // iterate through the prop and update each property with the one in loadedObject
object[item] = loadedObject[item] // Why does this work!?
}
}
}
},
Now this actually works, without errors or warnings. I don't understand why though. Normally when I try to modify a prop directly, Vue throws a warning at me:
[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders.
Instead of object[item] = loadedObject[item] I tried the following, but that actually failed:
const u = 'update:' + object + '.' + item
this.$emit(u, loadedObject[item] )
What would be the correct way to do this?
The correct way would be to not sync objects, because sync does not support that: https://github.com/vuejs/vue/issues/6241
Alternative solutions are:
Put the method in the parent
Sync each property as a separate prop
Use a data store: https://v2.vuejs.org/v2/guide/state-management.html