Search code examples
storesvelte

Svelte Store. Spread syntax is not merging - just adding


I am trying to add some brocolli to my basket in the svelte store I have created. My code adds the brocooli to the basket but then duplicates the baskets and adds a whole new basket to my store. Not sure if the problem is caused by my lack of understanding of javascript or svelte.

Desired result

  • Basket 1
    • Orange
    • Pineapple
  • Basket 2
    • Banana
    • Apple
    • Plum
    • walnut
    • hazelnut
    • nutmeg
    • broccoli

    ACTUAL RESULT

  • Basket 1
    • Orange
    • Pineapple
  • Basket 2
    • Banana
    • Apple
    • Plum
    • walnut
    • hazelnut
    • nutmeg
  • Basket 2
    • Banana
    • Apple
    • Plum
    • walnut
    • hazelnut
    • nutmeg
    • broccoli

    Link to svelte codebox where you can view and run code

    https://svelte.dev/repl/80d428000a3f425da798cec3450a59d4?version=3.46.2
    if you click the button you see that my basket is duplicating. I am just trying to add the brocooli to the basket.

    code below

    import { writable } from 'svelte/store';
    export const storeBaskets = writable([
       {
         "name": "Basket 1",
         "items": ["Orange", "Pineapple"]
       },
       {
         "name": "Basket 2",
         "items": ["Banana", "Apple","Plum","walnut","hazelnut","nutmeg"]
       }
     ])
    //Local functions
    export const add = (item,basketIndex) => { 
           storeBaskets.update(val => {        
            const newItems = [...val[basketIndex].items, item]
            const newBasket = {'name':val[basketIndex].name,'items':newItems}
            val = [...val,newBasket]
           return val
       })
    

    Solution

  • You might not need to spread, because it's an array, you'r spreading the existing items of the array and then adding the new basket to it. You can map and replace by basketIndex, like:

    export const add = (item,basketIndex) => { 
            storeBaskets.update(val => {
             const newItems = [...val[basketIndex].items, item]
             const newBasket = {'name':val[basketIndex].name,'items':newItems}
             
            return val.map((basket, i) => i === basketIndex ? newBasket : basket)
        })
    }
    

    (Working example)