13

How to get store value from another store? https://svelte.dev/repl/0ab80c2fb8e045958d844bd4b11c04a9?version=3.22.1

In the example I include a variable inputVal in stores.js file and changing in
set: (val) => {inputVal=val; set( val );}, and use in fn setToZero

Question: how to do it directly without using the inputVal variable?

lukaszpolowczyk
  • 605
  • 1
  • 7
  • 27

1 Answers1

38

Use get(store) to access a stores value.

Example:

import {get, writable} from 'svelte/store'

const myStore = writable(41)

const value = get(myStore)

If you are accessing a store from within a .svelte component, there is a shortcut. Just prefix the store name with $, eg. const value = $myStore.

joshnuss
  • 1,869
  • 14
  • 11
  • 5
    Minus of this solution: "This works by creating a subscription, reading the value, then unsubscribing. It's therefore not recommended in hot code paths." https://svelte.dev/docs#get – lukaszpolowczyk May 04 '20 at 14:30
  • 5
    Alternatives: 1) Use `store.subscribe(callback)`, the callback will be notified when the value changes. 2) Use a derived store `derived([storeA, storeB, ...], callback)`, when any dependent stores change your callback can produce a new (aggregate) value – joshnuss May 04 '20 at 22:00
  • 6
    @lukaszpolowczyk's link is now https://svelte.dev/docs#run-time-svelte-store-get – Nils Lindemann Jan 07 '22 at 15:34