Home > OS >  Cannot copy a Pinia state Array without referencing it
Cannot copy a Pinia state Array without referencing it

Time:09-05

I am trying to create a duplicate copy of an array in a Pinia store. This copy is used for creating a reactive object in different components which is used to model inputs. Only if the user wants to save the changes, the copy array should be used to overwrite the original array.

However, the original array also gets modified instantly whenever the copy array is modified as if it was just a reference

  import { defineStore } from 'pinia'

  export const useItemStore = defineStore('item', {
      state: () => ({
        items: ['foo', 'bar'],
        itemView: []
    }),

    actions: {
    initialize(){
        this.itemView = [...this.items] //create a copy of original items array
   },
    edit(newItems){
        this.itemView = newItems
    },
    save(){
        this.items= [...this.itemView ] //save the changes
    },
})

How can I create a copy of a Pinia array which can be edited without updating the original?

In my actual use case, items is an array of deep nested Objects so I cannot simply do an array map function and copy each item's value

CodePudding user response:

One approach to create a copy of a deeply nested object is to use

const copy = JSON.parse(JSON.stringify(items));

If importing a library is an option, lodash - cloneDeepcan be imported separately via the lodash.cloneDeep module. See the usage here

  • Related