Revise the elements within the array

I am currently working on a project that involves creating a dynamic product list similar to a shopping cart. I start by loading a series of products into an array of objects.

products = [
        {
            id: 1,
            name: "Product1",
        },
        {
            id: 2,
            name: "Product2",
        },
        {
            id: 3,
            name: "Product",
        },

];

To display the list of products using Svelte, I use the following code:

<div class="col-md-12 row grid">
    {#each products as product}
        <div class="card mt-2 g-col-3">
            <div class="row">
                <div class="col-md-8">
                    <div class="card-body">
                        <h5>{product.name}</h5>
                        <button
                            on:click={addProduct(product.id)}
                            class="btn btn-primary">Add Product
                        </button>
                        { "0 products"}
                    </div>
                </div>
            </div>
      </div>
    {/each}
</div>

Utilizing the addProduct() function, I update the inventory array each time a user adds a new product along with the quantity of units for that product.

let inventory =[];
const addProduct = id =>{
        
        let qty = 0;
        if(inventory.find(element => element.id === id))
        {
            qty = inventory.find(element => element.id === id).qty
            inventory=inventory.filter(element => element.id !== id)
            inventory.push({id:id,qty:qty+1});

        }
        else{       
        inventory.push({id:id,qty:1});
        }
        
    }

A challenge I am facing is updating the product count dynamically as users add items to their cart within each product section where it currently says { "0 products"}. Any suggestions or solutions are greatly appreciated!

Thank you!

Answer №1

When you need to show the number of items in inventory, you can achieve this by replacing { "0 products"} with

{inventory.find(element => element.id === product.id)?.qty ?? 0} products

Utilizing Optional chaining (?.) and Nullish coalescing operator (??)

In addition to updating inventory for reactivity purposes, there is a logical issue in the addProduct() function. If an element already exists, instead of adding a new one, you should modify the existing element as shown below:

function addProduct(id) {
        const element = inventory.find(element => element.id === id)
        if(element) {
            element.qty += 1
            inventory = inventory
        }
        else{       
            inventory.push({id:id,qty:1});
            inventory = inventory
        }
    }

Although the above code works well, it may be more efficient to use an object instead of an array for the inventory and make edits easier. Check out this REPL example for comparison.

<script>
    import {products} from './products'

    let inventory = {}

    function addProduct(id) {
        const entry = inventory[id]
        if(entry) {
            entry.qty += 1
            inventory = inventory
        }
        else{       
            inventory[id] = {qty:1}
            inventory = inventory
        }
    }
</script>

<div>
    {#each products as product} 
    <h5>{product.name}</h5>
    <button on:click={() => addProduct(product.id)}>
        Add Product
    </button>
    {inventory[product.id]?.qty ?? 0} products
    {/each}
</div>

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

jQuery button click event not registering

Confused by what should be a simple solution, I find myself struggling to figure it out at the moment. All I have is this button: <button id="logout" type="button">Logout</button> It's meant to trigger this jQuery code enclosed in script ...

Deactivate certain days in Material UI calendar component within a React application

Currently, my DatePicker component in React js is utilizing material-ui v0.20.0. <Field name='appointmentDate' label="Select Date" component={this.renderDatePicker} /> renderDatePicker = ({ input, label, meta: { touched, error ...

Is it normal for a Firebase listener to trigger twice when adding date to the database in React?

I've developed a basic chat application. Once the user submits a message, it is stored in the database along with their username. this.ref.child("/chat").update({username: this.state.username, message: this.state.chatMessage}); Subsequently, I ...

Issue with Vue 3 where radio input remains unchecked after being clicked

I'm currently facing an issue with radio buttons for answers in my questions. Whenever I click on an answer, the radio input does not stay checked and I am unable to disable the other options. My front-end is developed using Vue 3 and the back-end wit ...

Tips for organizing and sorting date data in a JSON datatable

I am working with two date input fields: <form id="refresh" method="post" action="income.php"> <input type="text" id="dari" name="dari" /> <input type="text" id="sampai" name="sampai" /> <button type="submit">Refresh</b ...

A guide to extracting text from HTML elements with puppeteer

This particular query has most likely been asked numerous times, but despite my extensive search, none of the solutions have proven effective in my case. Here is the Div snippet I am currently dealing with: <div class="dataTables_info" id=&qu ...

Find the position of the object in a list

I have an array that looks something like this data: Array(3) 0: data: Object account_id: (...) address_1: (...) address_2: (...) amount: 10.00 id: 1234 ... 1: data: Object account_id: (...) address_ ...

Async/Await moves on to the next function without waiting for the previous function to finish executing

I am developing a web application that requires querying my database multiple times. Each query depends on the data retrieved from the previous one, so I need to ensure each call completes before moving on to the next. I have attempted using async/await fo ...

Does repeatedly accessing count($array) in a foreach loop result in a decrease in performance?

While browsing through SO, I came across the query "Identifying the final element of an array when utilizing a foreach loop in PHP". In the discussions, user "johndodo" argued that there is no reduction in performance for repeatedly accessing count($array ...

Issue: The object is unable to be executed as a function, resulting in the failure to return an array

Currently, I am extracting table values from the UI row by row. This involves clicking on each row and retrieving the corresponding data. exports.getTableData = function(callback){     var uiArray =[];     var count;         aLib.loadCheck(c ...

Retrieving information from an unfamiliar encoding document

Our testing equipment, manufactured in 1995, is powered by MS DOS. The Analog-digital converter records information in a file. In [picture1] the structure of the file is revealed. [Picture2] displays the oscillogram that was created using data from the fil ...

"Enhance user experience with jQuery's text expansion and collapse

Figuring out how to collapse and expand text with a button click has been challenging for me. I managed to make the text collapse when the button is clicked, but now I also need it to expand back again. The goal is to have the text initially hidden, then e ...

Interactive Vue components with dynamic children and sub-children

In my Vue application, I have a component called Address.vue which contains a child component called Contact.vue. One address can contain multiple components What I have accomplished: I have implemented the functionality in the Address.vue component t ...

Storing information in a parse table using NodeJs

I am trying to add data to a Parse table. At the top of my code, I have the line import Parse from 'parse/node';. Here is how I am inserting the data: const game = Parse.Object.extend('Game'); const query = new Parse.Query(game); que ...

Excessive ajax requests occurring when the options in the form are altered

My website contains two main sections: (1) search criteria, which include selection boxes in a form used to access database information, and (2) a div where the results are displayed. The initial page load serializes default values from the form and sends ...

Revise Script to Duplicate Alt Attribute onto Miniatures

I'm customizing a gallery plugin for a website that I am currently developing, aiming to add support for titles. The script I am using can be found here: DEMO: http://jquery.malsup.com/cycle/pager2.html CODE: All the functionalities are in place e ...

Is it true that JavaScript Date.parse doesn't recognize Alaska Timezones?

When using JavaScript's Date.parse, it handles Pacific Time without any issues: Date.parse('June 20 2015 10:22 PDT') However, it encounters issues with Alaska Time: Date.parse('June 20 2015 10:22 AKDT') Does anyone have a relia ...

Ways to incorporate a dynamic value into a chart created with chart.js?

I want to create a doughnut chart representing the number of individuals who have tested positive for Coronavirus and the number of deaths related to it. How can I transfer the same data from the top container into the chart? The confirmedCases and deaths ...

Acquire a specific key based on a conditional subkey value in PHP

Can we simplify the process of searching for ID->22 in an array (where each ID is unique) and returning the parent key? Here is a sample code: foreach ($array as $key => $value) { if($value['date']->ID == 22) { echo $key; } } In th ...

Upgrade your input button style using jQuery to swap background images

I have an input button with an initial background image. When a certain condition changes, I want to update its image using jQuery without overriding the button's global CSS in the stylesheet. Is there a way to only change the background attribute wit ...