8

What is the correct way (or differences if both are correct) for updating a $orderItems = writable([]) Svelte writable array store? We'll assume result is a new item I want to push at the end of $orderItems.

orderItems.update(items => ([...items, result]))

or

$orderItems = [...$orderItems, result]
nimser
  • 620
  • 2
  • 9
  • 22

1 Answers1

10

Both are correct and another alternative would be

$orderItems.push(result)
$orderItems = $orderItems

and

orderItems.update(items => {
    items.push(result)
    return items
})

The difference is that the $ syntax can only be used inside components, so .svelte files. From the docs

Any time you have a reference to a store, you can access its value inside a component by prefixing it with the $ character. This causes Svelte to declare the prefixed variable, subscribe to the store at component initialization and unsubscribe when appropriate.

If you want to modify the store from a .js file, this can only be done via .set() / .update()

Corrl
  • 6,206
  • 1
  • 10
  • 36