Copying a Pinia state Array without referencing it is not possible

My goal is to duplicate an array within a Pinia store so that I can use it to create a reactive object in various components for input modeling. The intention is to only update the original array if the user decides to save any changes made using the copy array.

The issue is that whenever I modify the copy array, the original array also gets instantly modified as if they are referencing each other.

  import { defineStore } from 'pinia'

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

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

I am seeking a solution to create a independent copy of a Pinia array that can be edited without affecting the original one.

In my specific scenario, items consists of deeply nested Objects, which prevents me from simply using an array map function to copy each item's value.

Answer №1

To effectively create a duplicate of a complexly nested object, one method is to utilize the following code:

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

If incorporating an external library is feasible, consider importing lodash's cloneDeep function through the lodash.cloneDeep module. Refer to its implementation guidelines here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I keep encountering an error in the where clause when trying to update MySQL. What could be

I encountered an issue stating Unknown column 'CR0001' in 'where clause' while executing my code. Strangely, the error seems to be related to the id_scooter column rather than CR0001. Below is the snippet of my code: var update = "UPDA ...

Sequencing numerous promises (managing callbacks)

I am encountering some challenges with promises when it comes to chaining multiple ones. I'm having difficulty distinguishing how to effectively utilize promises and their differences with callbacks. I've noticed that sometimes callbacks are trig ...

What is the best way to display my 'React Loading Spinner' component at the center of my view?

Whenever I use the Loading as my parent component for the Layout component, it always shows up in the center of the page instead of within my view. How can I adjust its positioning? ...

Add the slide number and total count in between the navigation arrows of the owl carousel

In my Angular application, I am utilizing an ngx owl carousel with specific configurations set up as follows: const carouselOptions = { items: 1, dots: false, nav: true, navText: ['<div class='nav-btn prev-slide'></div>' ...

Create a constructor that takes in inputs and adds them to an array

My current challenge involves working with a class that has a constructor and utilizing it within an array. Unfortunately, when attempting to do so, I encounter an error. Here is the snippet of code in question: using System; class ClassA { public ...

Understanding how Vue CLI v3 determines which JavaScript files should be separated into different chunks

Struggling to grasp the new CLI and configuration adjustments. The official documentation lacks details on incorporating CSS as an entry point instead of directly importing it into a component or main.js. Noticing that some JS files are being split into s ...

Implementing a Custom Authentication Backend in Next.js Without next-auth: A Strategic Method

Currently, I am delving into the realm of Next.js 13 for development with little familiarity in Server-Side Rendering (SSR). The obstacle I face pertains to utilizing my own backend API built on Express.js. This backend service already supports essential ...

When submitting a form with the jQueryForm plugin, take action on the form by selecting it with `$(this)`

I have a situation where I have multiple forms on one page and am utilizing the jQuery Form plugin to manage them without having to reload the entire page. The issue arises when I need some sort of visual feedback to indicate whether the form submission wa ...

Processing JSON data from an array in PHP

Currently, my code involves utilizing an AJAX request to retrieve data from a database dynamically. The data received is processed by the PHP function json_encode() before being sent back to AJAX. Upon receiving the data through the AJAX request, it is for ...

Module for React Native that enables users to select and copy text within a specified view

Is there a feature that enables users to highlight and copy text from within a view? If not, is there a method to identify all "Text" type elements and extract the text they contain? <View> <Text>Text1</Text> <Text>Text2</Text& ...

Leveraging a component with a singular prop

After delving into the Vuejs documentation, I have found it to be quite perplexing. The lack of complete examples, despite snippets being provided, has made understanding concepts such as using a single prop instead of creating multiple properties for each ...

"You might require a suitable loader for managing this file format since there are currently no loaders set up to handle it."Webpack, vue.js

Having trouble with images in Vue.js Webpack Here's my Vue.js template: https://i.stack.imgur.com/h1zYx.png (ignore the red-line) This is my package.json: https://i.stack.imgur.com/v9rCD.png As well as webpack.config.js: https://i.stack.imgur.com ...

Tips for eliminating additional white space within a bootstrap row

I'm having trouble removing the extra space on my website while using Bootstrap 5. I've tried various Bootstrap classes like pr-0, mr-0, p-auto, m-auto but none of them seem to work. I also attempted using CSS margin-right: 0; but that didn' ...

After cloning the variable from props, the Vue 3 Composition API variable becomes undefined

I have a main component containing code and tables, including a modal that is displayed based on a boolean value. The main component features the following modal: <ConfirmPaymentModal ref="confirmPaymentModal" :invoice="markAsPa ...

Node JS Client.query not returning expected results

Currently, I am developing a Web Application that interacts with my PostgreSQL database. However, when I navigate to the main page, it should display the first element from the 'actor' table, but unfortunately, nothing is being retrieved. Below i ...

Convert JSON objects within an array into HTML format

Is there a way to reformat an array of JSON objects that has the following structure? [{"amount":3,"name":"Coca-Cola"},{"amount":3,"name":"Rib Eye"}] The desired output in plain HTML text would be: 3 - Coca-Cola 3 - Rib Eye What is the best approach to ...

Utilizing a React hook to render and map elements in a function

Can the hook return function be assigned to a render map in React? In this example, we have the socialAuthMethodsMap map with the onClick parameter. I tried to assign the signInWithApple function from the useFirebaseAuth hook, but it violates React's ...

Is it possible for the data submitted in a POST request to be converted into URL parameters?

Our technology stack: Frontend built with Vue.js and utilizing the vuetify component library Custom Python middleware REST API using Flask + Tornado External Matomo setup connected to the frontend via the vue-matomo plugin system (https://github.com/Amaz ...

Passing a return value to ajax success within an Express application

I am trying to retrieve a value from an included file and use it in the success function of an ajax call within Express. Below is my code for app.js: var userdetail = { "useremail":req.body.useremail, "fname" : req.body.fname, "lname" : req.bo ...

Handling 404 Response from WebAPI in $Http.get() Function

While using my web application, I am executing a GET command to access a remote HTTP WebAPI service. $http.get(url).then(function(data) { do_something(); }); When the WebAPI successfully returns data, everything functions as expected. However, in cases w ...