How to add a dynamic value to a Svelte store, based on values sourced from a HTML dropdown box on page

I'm playing around with Svelte code, as part of building a very simple shopping basket/store, and have an issue I can't resolve!

Issue:

I want to update a specific property in an array of objects, that have been consumed in a Svelte writable store, but any change I make seems to be ignored!

Background:

I have a Svelte writable store, defined as:

let products = writable(myjson.default);

This consists of 6 objects in an array, similar to this:

[
{
  "id": 1,
  "name": "Italian House Blend",
  "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam ac tellus finibus, molestie purus id, placerat augue. Sed in arcu placerat, ultricies nibh et, auctor dolor.",
  "image": "/images/1.png",
  "large_image": "/images/1_large.png",
  "price": 18,
  "quantity": 1,
  "variant": ""
},...

I'm looking to update the variant entry - this will be with one of three entries: Coarse, Fine, WholeBean. These are sourced from a drop-down within my product card component.

The values for the dropdown are sourced from this:

  let questions = [
    { id: 1, text: `Coarse` },
    { id: 2, text: `Fine` },
    { id: 3, text: `Whole Bean` }
  ];

... and I have a #each block that iterates through and correctly displays the text value on screen. The dropdown box is bound to allow two-way updates (this is done via a property called selected)

I have been able to console.log out the value of selected in my addToCart function - this displays the selected value:

const addToCart = (product) => {
    console.log("selected", selected)
    for (let item of $cart) {
      if(item.id === product.id) {
        product.quantity += 1
        product.variant = selected.text  <---- SOURCE OF PROBLEM??
        $cart = $cart;
        return;
      }
    }
    $cart = [...$cart, product]
    console.log("cart", $cart)
  }

The issue I have is I want to add the selected.text property to the array of objects, so I end up with this in console.log, and can then pipe out the variant property at a later stage:

cart 
[{…}]
0:
description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam ac tellus finibus, molestie purus id, placerat augue. Sed in arcu placerat, ultricies nibh et, auctor dolor."
id: 1
image: "/images/1.png"
large_image: "/images/1_large.png"
name: "Italian House Blend"
price: 18
quantity: 1
variant: "<<NAME APPEARS HERE>>"
__proto__: Object
length: 1
__proto__: Array(0)


Read more here: https://stackoverflow.com/questions/67391410/how-to-add-a-dynamic-value-to-a-svelte-store-based-on-values-sourced-from-a-htm

Content Attribution

This content was originally published by Alex Libby at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: