DEV Community

Lam Hoang
Lam Hoang

Posted on • Originally published at simplecheatsheet.com

Store in Svelte

A store is simply an object with a subscribe method that allows interested parties to be notified whenever the store value changes:

<script>
  let countValue;
  const unsubscribe = count.subscribe(value => {
    count_value = value;
  });
  onDestroy(unsubscribe);
</script>

<h1>The count is {count_value}</h1>
Enter fullscreen mode Exit fullscreen mode

Update the stored value:

<script>
  function increment() {
    count.update(n => n + 1)
  }
</script>
Enter fullscreen mode Exit fullscreen mode

Set a value:

<script>
  function reset() {
    count.set(0);
  }
</script>
Enter fullscreen mode Exit fullscreen mode

Usage
Use auto-subscription to get rid of subscribe and onDestroy methods:

<script>
  import { storeValue } from './AnotherComponent'
  // ...other imports come after
</script>

<h1>The count is {$storeValue}</h1>
Enter fullscreen mode Exit fullscreen mode

Readable store

<script>
  export const time = readable(new Date(), function start(set) {
    // Implementation
    set()

    return function stop() {
      // Implementation
    }
  })
</script>
Enter fullscreen mode Exit fullscreen mode

Writable store

<script>
  import { writable } from 'svelte/store';

  const count = writable(0, () => {
    console.log('got a subscriber');
    return () => console.log('no more subscribers');
  });
</script>
Enter fullscreen mode Exit fullscreen mode

Derived store

…from another store.

<script>
  import { derived } from 'svelte/store';

  const delayed = derived(time, ($a, set) => {
    setTimeout(() => set($a), 1000);
  }, 'one moment...');

  // or (read-only derived):

  const elapsed = derived(time, $time =>
    Math.round(($time - start) / 1000)
  );

</script>
Enter fullscreen mode Exit fullscreen mode

Custom store

// store.js

import { writable } from 'svelte/store';
function createCount() {
  const { subscribe, set, update } = writable(0);

  return {
    subscribe,
    increment: () => update(n => n + 1),
    decrement: () => update(n => n - 1),
    reset: () => set(0)
  };
}
export const count = createCount();
Enter fullscreen mode Exit fullscreen mode

In the component:

<script>
  import { count } from './store.js';
</script>

<h1>The count is {$count}</h1>

<button on:click={count.increment}>+</button>
<button on:click={count.decrement}>-</button>
<button on:click={count.reset}>reset</button>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)