Encountering an unusual issue with JSON in a Vuex getter: it appears to be causing a pass-by-reference problem. To provide some context - I'm currently working on a music application that consists of various "scenes", each containing collections of "tracks" (similar to Ableton Live).
Here is the getter code:
newTrack: state => {
let newTrack = JSON.parse(JSON.stringify(state.newTrackDefaults))
return newTrack
},
This is the object being referenced:
newTrackDefaults: {
tune: [],
// other properties here
},
And it's used in this action:
setUpNewScene: context => {
let newScene = JSON.parse(JSON.stringify(context.state.newSceneDefaults))
let newTrack = context.getters.newTrack
console.log(newTrack) // revealing the issue lies with the getter
newScene.tracks.push(newTrack)
context.commit('addNewScene', newScene)
}
The problem arises when adding items to a track in the initial scene, then creating a new scene where the new scene automatically inherits the same track as the first scene. This discrepancy is visible not only in the rendering but also in the Vuex state (as per DevTool observations). Additionally, any updates made to tracks in the first scene are reflected in the tracks of the new scene, suggesting a pass-by-reference error.
After several console.log
tests, it was discovered that the getter was returning the "filled" track. The issue was resolved by bypassing the getter and modifying the action as follows:
setUpNewScene: context => {
let newScene = JSON.parse(JSON.stringify(context.state.newSceneDefaults))
let newTrack = JSON.parse(JSON.stringify(context.state.newTrackDefaults))
console.log(newTrack) // now functioning correctly
newScene.tracks.push(newTrack)
context.commit('addNewScene', newScene)
}
Although a solution has been implemented, there remains confusion surrounding the original behavior. Could the getter somehow interfere with the JSON
functions? What could potentially be causing this unexpected outcome?