Why is my companion object being updated along with my target?

Viewed 26

I have set up the following Reactive:

let blank = {
    id: "new",
    label: "",
    details: "",
    status: "",
    due_date: "",
    deadline: "",
    enthusiasm: '0',
    allotted: 30,
}

const state = reactive({
    tray: "default",
    active: null,
    task: {
        current: blank,
        proposed: blank
    }
})

and in one of my components, I am adding data like so:

setup() {
    const store = inject('store')

    async function refresh() {
      if (store.state.active !== null) {
        const response = await store.methods.loadTaskData(store.state.active)
        store.state.task.current = response.data.results
        store.state.task.proposed = response.data.results
      }
    }
    watch(() => store.state.active, () => {
      refresh()
    })
    refresh()

    return {store, ...toRefs(store.state.task)}
}

With this, when I use v-model to update fields in the proposed object, for some reason it also updates the corresponding fields in the current object as well.

<input
  v-model="proposed.label"
  type="text"
  class="form-field"
> 
// Updates both "current" and "proposed" objects.

However, if I remove this line:

store.state.task.current = response.data.results

thereby leaving the "current" object blank, then everything works fine. Changes made to proposed aren't reflected in current. So how do I add response.data.results to both the current and proposed objects without having the wires get crossed like this?

1 Answers

Both current and proposed are being initialized as the same object. Instead, assign a copy of blank...

task: {
    current: { ...blank },
    proposed: { ...blank }
}
Related