Include information in the array and remove any existing data

I am attempting to add an element to an array without deleting other content, and it seems very straightforward... Array.push()

My issue is that I am utilizing ref([]) and I have read that I can use ref.value.push = newItem

However, the problem is that it overrides my previous content. I need the user to select a checkbox with information, and this information should be added to my table. To achieve this, I'm implementing:

<input type="checkbox" :id="item.id" :name="item.name" :data-category="item.category.name" style="font-size: 0.6em; transform: scale(1.6);" @change="addToCart($event)"/>

and my function addToCart():

const addItemCart = ref([])
    const addToCart = (event) => {
        let itemId = event.target.id
        let itemName = event.target.name
        let category = event.target.getAttribute("data-category")

        var newItem = new Array();
        newItem = [{ id: itemId, name: itemName, category: category }];
             
        addItemCart.value = newItem
    }

I tried using:

const addItemCart = ref([])
    const addToCart = (event) => {
        let itemId = event.target.id
        let itemName = event.target.name
        let category = event.target.getAttribute("data-category")

        var newItem = new Array();
        newItem = [{ id: itemId, name: itemName, category: category }];
             
        addItemCart.value.push = newItem
        console.log(addItemCart.value)
    }

This returns:

Proxy(Array) {push: Array(1)}

[[Handler]]:Object
[[Target]]: Array(0)
push: Array(1)
0: {id: '96', name: 'DESINCRUSTADOR DCALUXE - HIDROCAL ELECTRONICO', category: 'ARTICULOS B'}
length: 1
[[Prototype]]: Array(0)
length: 0
[[Prototype]]: Array(0)
[[IsRevoked]]: false
app.js:20948 

Proxy(Array) {push: Array(1)}
[[Handler]]: Object
[[Target]]: Array(0)
push: Array(1)
0: {id: '281', name: 'DCALUXE PRO 2.0 DESINCRUSTADOR ELECTRONICO', category: 'ARTICULOS B'}
length: 1
[[Prototype]]: Array(0)
length: 0
[[Prototype]]: Array(0)
[[IsRevoked]]: false

The data is not being pushed into my array and I cannot display it in my table. I have the following code for looping through:

<tr v-for="item in addItemCart" :key="item">
    <td>{{ item }}</td>
    <td>{{ item.id }}</td>
    <td>{{ item.name }}</td>
    <td>{{ item.category }}</td>
    <td><i class="fa fa-trash" aria-hidden="true" @click="removeItem($event)"></i></td>
</tr>

My question is, how can I add items to my array without deleting my other content?

Thank you for reading and sorry for my poor English.

Answer №1

Consider utilizing the push method as a function and supplying the new object as an argument:

const addToCartItems = ref([])
const addItemToCart = (event) => {
    let itemId = event.target.id
    let itemName = event.target.name
    let category = event.target.getAttribute("data-category")
          
    addToCartItems.value.push({ id: itemId, name: itemName, category: category })
    //In this code snippet, we add the new item as an object to `addToCartItems.value`
}

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

Troubleshooting: Why does MatchInlineSnapshot not work in Vue 3 CLI jest testing?

Experiencing a problem with my Vue project as ToMatchInline Snapshot isn't functioning and causing test failures https://i.sstatic.net/xDJ8b.png Any suggestions? Sharing my config file below https://i.sstatic.net/BDVNa.png Even attempted using rend ...

What could be causing my Material UI Divider to appear invisible within a Material UI Container or Paper component?

Hey there! I am absolutely smitten with Material UI - it's incredibly versatile. However, I'm facing a bit of trouble with the Material UI Divider not displaying when nested within either a Container or Paper component. I've looked into it ...

Enlist partial components in express-handlebars

I'm having trouble registering partials in my app. Despite trying various solutions from other sources, nothing seems to work for me... I have set up the express handlebars as follows: import { engine } from 'express-handlebars'; const __fi ...

Encountered an error while attempting to convert react-native-reanimated-65-jsc.aar

ERROR: App installation failed after 19 seconds Failed to install the app. Ensure your Android development environment is properly set up. Follow this link for setup instructions: https://reactnative.dev/docs/environment-setup. Erro ...

Retrieving Text Between HTML Tags Using jQuery

Disclosure: I am fully aware of the messy HTML code in this legacy application. Unfortunately, due to its extensive dependencies, making any changes to the HTML structure is not feasible. Despite the circumstances, here is the code snippet at hand: <t ...

Breaking down a CSV file in VBA to create a multidimensional array

My .csv file has the following structure: [TestHeader]FIELDS,"LANGUAGE","LC_NUMERIC","CELLNAME","TESTTYPE","REPORTER","TITLE","STARTDATE","STARTTIME","ENDDATE","ENDTIME"DATATYPE,"Text(80)","Text(80)","Text(64)","Text(80)","Text(80)","Text(80)","Text(12)"," ...

What is the best way to initiate a Bootstrap carousel so that it begins with the first image every time a modal window appears

I am in the process of creating my own portfolio to showcase my work. I have implemented a feature where clicking on an image opens up a Bootstrap carousel. However, I'm facing an issue where the carousel doesn't always start with the first imag ...

Ways to trigger an alert once a div is fully loaded with content

I have a webpage with a search feature. When the user clicks the search button, the results are fetched via ajax from the database and displayed in a div. After the results are displayed, I want to perform an action as soon as the total count of records i ...

Prevent parent from scrolling when hovering over a div in HTML5

Unfortunately, the scrolling attribute is not supported in HTML5. I'm facing an issue where I have an svg inside an iframe within a div, and I need to enable scroll functionality within the div while preventing the page from scrolling at the same time ...

Updating the DOM after scrolling using jQuery

jQuery hover functionality is not working correctly after scrolling. $(document).ready(function() { $('img').hover(function(){ alert('hello'); },function(){ alert('hello not'); }); }); When hoveri ...

What is the best way to retrieve the latest state after applying useEffect to trigger an onChange event for an element?

I am encountering an issue with an input field in my component that requires an onChange event to update the state. Despite binding the onChange event on mounting the component, the state remains unchanged as the onChange event seems to have the initial st ...

Struggling with loading react storybook

I am having trouble getting my storybook app to start. It is stuck in a loading state with no errors showing in the console. Can anyone help me figure out what I am doing wrong? Check out the screenshot here storybook/main.js const path = require(' ...

React state change does not effectively adjust Grid Size

I am facing an issue with adjusting the grid size in my Conway game of life app. Whenever I click on the buttons to change the numCols or numRows, only one of them gets updated in the app. How can I effectively update the state so that the grid changes siz ...

What are the alternative options for converting a collection to an

I've been working on a basic route that uses the toArray() method to send data back to an external application. It's functional, but I'm looking for a way to send the data as JSON objects rather than an array. Below is my current code. Is t ...

Is there a way to shorten the length by left-clicking and increase it by right-clicking?

Illustration: section.my{margin: 20px;} <section class="my"></section> Hover over: section{padding: 10px;} Double click: section{border: 1px solid black;} ...

Searching for image labels and substituting the path string

Upon each page load, I am faced with the task of implementing a script that scans through the entire page to identify all image src file paths (<img src="/RayRay/thisisianimage.png">) and then add a specific string onto the file paths so they appear ...

What is the best way to update a table component on the screen in Vue after making changes to the JSON data?

Currently, I am at a beginner level and learning Vue. My main focus right now is to have the table in my application reload or re-render itself so that any changes made to the db.json file are reflected on the screen. I've implemented a modal that all ...

Problem encountered with @HostListener

In an Angular component, I have the following code snippet that is functioning as intended: @HostListener('document:click', ['$event']) onClick(event) { if(!this.eRef.nativeElement.contains(event.target)) { console.log("clicked out ...

Scrolling on a div can be used to create a looping magnification or scaling

Is there a way to create a seamless loop between #box2 and #box using this fiddle? I want them to reveal themselves in a continuous loop with infinite scroll. Each time one box fills the frame, the next one should appear in the distance, repeating indefini ...

Retrieve a text and save it into a variable

Is there a way to extract a specific string and save it as a variable? For example, if I have the following URL: http://sub.site.com/WordsHere-t.jpg I am looking to extract just WordsHere. The length of this string can vary and will not always be 9 chara ...