Can someone explain how I can extract values from components that have been added using a for each loop in Svelte

Embarking on my journey in frontend development and Svelte, I decided to dive into some experimentation.

Here is a counter component with buttons to increment or decrement the number of items:

Counter.svelte

<script>
    export let quantity = 0;
    function increase() {
        quantity += 1;
    }

    function decrease() {
        if (quantity > 0) {
            quantity -= 1;
        }
    }
</script>


<button on:click={decrease}>-</button>{quantity}<button on:click={increase}>+</button>

App.svelte

<script>
... import dependencies

    let products=[{ //data fetched from API
      id: 1,
      name: "potato",
      price: 5
    }, {
      id: 2,
      name: "garlic",
      price: 3
    }, {
      id: 3,
      name: "rice",
      price: 10
    }];

    function checkout() {
        //TODO: Send JSON data through POST request
    }
</script>

{#each products as product}
    {product.name} <Counter></Counter>
{/each}

<button on:click={checkout}>Checkout</button>

I'm wondering how to construct the following JSON object when the selected quantity for an item is greater than 0 after clicking the button. (assuming garlic has a quantity of 0)

    [{
      id: 1,
      name: "potato",
      price: 5,
      quantity: 30
    },{
      id: 3,
      name: "rice",
      price: 10,
      quantity: 400
    }];

Answer №1

One can assign a value within the #each loop to a property of the individual item

{#each items as item}
    {item.name} <Counter bind:amount={item.amount}/>
{/each}

Even though the property may not exist initially, having a default value set inside Counter

export let amount = 0;

will initialize it to zero. Any changes made to the amounts will then directly impact the items array. Therefore, within the purchase function, simply filter items for those with a non-zero amount

    function purchase() {
        const itemsWithAmount = items.filter(i => i.amount > 0)
        console.log(itemsWithAmount)
    }

REPL

<script>
    import Counter from './Counter.svelte'

    let items=[{
        id: 1,
        name: 'potato',
        price: 5
    }, {
        id: 2,
        name: 'garlic',
        price: 3
    }, {
        id: 3,
        name: 'rice',
        price: 10
    }];

    $: console.log(items)

    function purchase() {
        const itemsWithAmount = items.filter(i => i.amount !== 0)
        console.log(itemsWithAmount)
    }
</script>

<ul>
    {#each items as item}
    <li>
        {item.name} <Counter bind:amount={item.amount}/>
    </li>
    {/each}
</ul>

<button on:click={purchase}>Purchase</button>

Answer №2

It is recommended to set the amount attribute of all items to 0 once the data is retrieved, so that it can easily be linked to the Counter:

<Counter bind:amount={item.amount} />

The bind function ensures that any changes made in the component are reflected in the item objects.

When making a purchase, you can simply filter the items as follows:

const toBuy = items.filter(x => x.amount > 0);

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

To subscribe to the display of [Object Object], you cannot use an *ngIf statement without being inside an *ngFor loop

In my angular Quiz project, I have a functionality where every user can create quizzes. I want to display all the quizzes that a logged-in user has completed. Here is how I attempted to achieve this: // Retrieving user ID and category ID inside Re ...

Mismatched data types caused by immutability

I'm having trouble with my object that has a middleware property and the types aren't working as expected. The error message is stating that the two middlewares are incompatible because one of them is set to readonly. Does anyone know how I can r ...

What is the most effective method to query Prisma using a slug without utilizing a React hook?

Retrieve post by ID (slug) from Prisma using getStaticProps() before page generation The challenge arises when attempting to utilize a React hook within getStaticProps. Initially, the plan was to obtain slug names with useRouter and then query for a post ...

Is there a way to modify the button's color upon clicking in a React application?

I am a beginner in the world of React and currently exploring how to utilize the useState hook to dynamically change the color of a button upon clicking. Can someone kindly guide me through the process? Below is my current code snippet: import { Button } ...

The class instances are not invoking the decorators

I'm experiencing issues with my decorators. It seems that the decorators are not being invoked on every instance of the class. While I understand that decorators are called during declaration time, I am wondering if there is a way to call them for eac ...

Generate a fresh Array by evaluating the properties provided by an Observable

I am working with an observable called myObservable$ that provides a specific array of objects: [ { "firstProp": "A", "secondProp": "NA", "available": false }, { "firstProp": "B", &quo ...

Exporting third-party types in an npm package

I recently developed an npm package that relies on types from the DefinitelyTyped repository. I added these types as devDependencies in the npm package and was able to use them without any issues, like so: export class Example { constructor (options: Ex ...

I encountered a SyntaxError while parsing JSON due to an absence of a number after a minus sign at position 1

I am trying to use the replicate model visoar/product-photo:edf42659dae0da88a26dba4912e7e4bb6c2fba25b1e1c6a5464cf220e467bce0, but when I provide it with an image and a prompt like on this page.tsx: "use client" import { LandingNavBar } from &apo ...

What is the best way to inform TypeScript that it is acceptable to reference an export that may or may not exist in the current revision of a module?

Using React's Profiler in Production is my aim, but the version of React I am currently using is React 16.5, which exports the unstable_Profiler. The team responsible for delivering an optimized asset bundle (including React) will be updating to Reac ...

Can a form be submitted using ViewChild in Angular5?

Can a form be submitted using ViewChild in Angular5? If so, how can it be achieved? I attempted to do this but was unsuccessful My Attempt: <form #form="ngForm" (submit)="submitForm(form)" novalidate> <input required type="text" #codeReques ...

Using the Ajax method from a separate class in TypeScript: A step-by-step guide

Recently, I started learning about typescript and ajax. One of the challenges I encountered was while creating a method in typescript for making ajax calls that can be used across classes: myFunc(value: string): JQueryPromise<any> { var dfd = $. ...

Guide to activating data transfer object validators in NEST JS

I have recently started using NEST JS and I am currently working on implementing validators in DTO's. This is what my code looks like: // /blog-backend/src/blog/dto/create-post.dto.ts import { IsEmail, IsNotEmpty, IsDefined } from 'class-validat ...

Why is my Angular app displaying outdated data from Firebase when navigating between pages?

Currently, I am dealing with an Angular 9 application that is hosted on Firebase and utilizes Firestore for its data storage. There is a perplexing issue that I haven't been able to figure out completely despite simplifying the app extensively. I will ...

Configuring Angular routes based on service method invocation

I have my routes configured in @NgModule. I also have a service that determines which parts of the application to display based on specific conditions. I need to call this service and adjust the routes according to its output. Issue: The route configurati ...

Using React Material UI in VSCode with TypeScript significantly hampers autocompletion speed

When including the "@mui/material", Visual Studio Code may become unresponsive, leading to Typescript warnings appearing after 10-15 seconds instead of the usual less than 10 milliseconds. For example: import { Button } from '@mui/material&a ...

Setting up a Typescript project using webpack

Greetings! I am looking to set up Typescript with composite config and webpack (everything worked fine with just a single tsconfig.json). I must admit that I am new to TypeScript and have been more familiar with JavaScript. My main issue is getting the des ...

Switching TypeScript: transitioning typeof into an instance

Can someone help me understand how to tell TypeScript that a function returns instances of a specified class? class A extends HTMLElement { color: 'white' } function builder<T extends typeof HTMLElement>(classParam: T) { let instance ...

Utilize TypeScript to define the types based on the return values produced by an array of factory functions

My application features multiple factory functions, each returning an object with specific methods (more details provided below). I am interested in creating a type that combines the properties of all these returned objects. const factoryA = () => ({ ...

Is there a way to transfer data to a different component in React without relying on a hierarchical parent-child relationship?

I am struggling to pass the data from the "SearchingData" Component to the "Search" Component. The SearchingData component is a child of the Search component. I need to transfer the data from the variable named "datacame" to the Search Component. Can som ...

The issue TS2305 arises when trying to access the member 'getRepositoryToken' from the module "@nestjs/typeorm" which is not exported

Recently, I've been exploring the world of Nestjs and TypeOrm packages, but I've stumbled upon a series of TS errors that have left me perplexed. While I've managed to resolve many of them, there's one persistent error that continues t ...