I'm new to Svelte Store. Here in svelte tutorial, they used update()
method in <Incrementer/>
and <Decrementer/>
components to update value. But in <Resetter/>
, they used set()
method to reset value. What exactly is the difference between update()
and set()
method in svelte store?
Asked
Active
Viewed 9,314 times
22

Abir Sheikh
- 463
- 4
- 9
1 Answers
37
From the docs:
set
is a method that takes one argument which is the value to be set. The store value gets set to the value of the argument if the store value is not already equal to it.
update
is a method that takes one argument which is a callback. The callback takes the existing store value as its argument and returns the new value to be set to the store.
So you can use update
if the next value should be dependent on the current value.
Also: update
only exists for convenience and is not part of the "store contract":
- A readable store only requires the
subscribe
method - A writable store requires the
set
method
Component code like $store = value
uses set
internally.

H.B.
- 166,899
- 29
- 327
- 400
-
1`So you can use update if the next value should be dependent on the current value` => this line answers my question. Thanks. – Abir Sheikh Feb 12 '22 at 11:22
-
1But then you could use update in every case, why set() even exists? – Knemay Jul 09 '22 at 02:11
-
1@Knemay `set` is simpler than `update`, you do not need to pass a function. – H.B. Jul 09 '22 at 10:24
-
this help me understands set and update. Basically they are the same, use as you like haha – angry kiwi Mar 12 '23 at 16:40