Runtime
Stores
The svelte/store
module exports functions for creating readable, writable and derived stores.
Keep in mind that you don't have to use these functions to enjoy the reactive $store
syntax in your components. Any object that correctly implements .subscribe
, unsubscribe, and (optionally) .set
is a valid store, and will work both with the special syntax, and with Svelte's built-in derived
stores.
This makes it possible to wrap almost any other reactive state handling library for use in Svelte. Read more about the store contract to see what a correct implementation looks like.
writable
Function that creates a store which has values that can be set from 'outside' components. It gets created as an object with additional set
and update
methods.
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.
If a function is passed as the second argument, it will be called when the number of subscribers goes from zero to one (but not from one to two, etc). That function will be passed a set
function which changes the value of the store. It must return a stop
function that is called when the subscriber count goes from one to zero.
Note that the value of a writable
is lost when it is destroyed, for example when the page is refreshed. However, you can write your own logic to sync the value to for example the localStorage
.
readable
Creates a store whose value cannot be set from 'outside', the first argument is the store's initial value, and the second argument to readable
is the same as the second argument to writable
.
derived
Derives a store from one or more other stores. The callback runs initially when the first subscriber subscribes and then whenever the store dependencies change.
In the simplest version, derived
takes a single store, and the callback returns a derived value.
The callback can set a value asynchronously by accepting a second argument, set
, and calling it when appropriate.
In this case, you can also pass a third argument to derived
— the initial value of the derived store before set
is first called.
If you return a function from the callback, it will be called when a) the callback runs again, or b) the last subscriber unsubscribes.
In both cases, an array of arguments can be passed as the first argument instead of a single store.
get
Generally, you should read the value of a store by subscribing to it and using the value as it changes over time. Occasionally, you may need to retrieve the value of a store to which you're not subscribed. get
allows you to do so.
This works by creating a subscription, reading the value, then unsubscribing. It's therefore not recommended in hot code paths.