Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way for updating a Svelte writable array store?

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]
like image 352
nimser Avatar asked Jan 01 '26 06:01

nimser


2 Answers

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()

like image 174
Corrl Avatar answered Jan 05 '26 21:01

Corrl


Even easier (with just one assignment):

$orderItems[$orderItems.length] = result
like image 37
Forna Avatar answered Jan 05 '26 20:01

Forna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!