Getter values are overwritten when return value is an array and is passed to ref #1162
-
Reproductionhttps://stackblitz.com/edit/github-kwwys9-s4mss8?file=src%2FApp.vue Steps to reproduce the bug
Expected behavior
Actual behavior
Additional informationNot sure if the information I gave in my expected/actual behaviour steps is too specific to the example, but more generally: If a getter returns an array, and that array is passed to a ref as its initial value, then updating an element of the ref array also causes the getter's return value to be updated. I have a suspicion I simply don't understand refs well enough, but I've read a lot of the docs and examples, and can't see where I'm going wrong! What we want to do is:
This seemed like the 'correct' way to do that. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
This is expected in terms of JS, you are copying the references to the same objects (e.g. https://www.freecodecamp.org/news/primitive-vs-reference-data-types-in-javascript/). If you want to create a copy, you need to copy the array and objects: const store = useCatDogStore();
const dogs = ref(store.catsAsDogs.map(c => ({...c}))); Also note that using destructuring for getters and state won't always work, so it's prefered to use |
Beta Was this translation helpful? Give feedback.
This is expected in terms of JS, you are copying the references to the same objects (e.g. https://www.freecodecamp.org/news/primitive-vs-reference-data-types-in-javascript/). If you want to create a copy, you need to copy the array and objects:
Also note that using destructuring for getters and state won't always work, so it's prefered to use
storeToRefs()
(https://pinia.vuejs.org/core-concepts/#using-the-store)