22

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?

Abir Sheikh
  • 463
  • 4
  • 9

1 Answers1

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