Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot copy a Pinia state Array without referencing it

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

like image 456
user3629023 Avatar asked Oct 13 '25 07:10

user3629023


1 Answers

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

like image 54
Abito Prakash Avatar answered Oct 14 '25 20:10

Abito Prakash