0
0
SvelteHow-ToBeginner · 4 min read

How to Create a Readable Store in Svelte: Simple Guide

In Svelte, create a readable store using the readable function from svelte/store. It lets you define a store with a value that updates automatically but cannot be set directly by components.
📐

Syntax

The readable store is created by importing readable from svelte/store and calling it with two arguments:

  • initialValue: The starting value of the store.
  • start: A function that receives a set callback to update the store value and returns a cleanup function.

This pattern allows the store to update internally but prevents external direct modification.

javascript
import { readable } from 'svelte/store';

const store = readable(initialValue, (set) => {
  // setup code here
  // call set(newValue) to update

  return () => {
    // cleanup code here
  };
});
💻

Example

This example creates a readable store that tracks the current time, updating every second automatically. Components can subscribe to it but cannot change the time manually.

javascript
import { readable } from 'svelte/store';

export const time = readable(new Date(), (set) => {
  const interval = setInterval(() => {
    set(new Date());
  }, 1000);

  return () => clearInterval(interval);
});
Output
The store updates every second with the current time value.
⚠️

Common Pitfalls

Common mistakes when using readable stores include:

  • Trying to call set outside the start function, which is not allowed.
  • Not returning a cleanup function, causing memory leaks.
  • Confusing readable with writable stores and expecting to update the store from components.
javascript
/* Wrong: Trying to update store outside start function */
import { readable } from 'svelte/store';

const wrongStore = readable(0, (set) => {
  set(1); // OK here
  return () => {};
});

// wrongStore.set(2); // Error: set is not a function

/* Right: Only update inside start function */
const rightStore = readable(0, (set) => {
  set(1); // update allowed here
  return () => {};
});
📊

Quick Reference

readable Store Cheat Sheet:

  • readable(initialValue, start): Creates a read-only store.
  • start(set): Function to update store internally.
  • Returns a cleanup function to stop updates.
  • Subscribers get updates but cannot set value.

Key Takeaways

Use readable from svelte/store to create stores that update internally but cannot be set externally.
The start function receives a set callback to update the store value and must return a cleanup function.
Do not try to call set outside the start function or from components.
Always return a cleanup function to avoid memory leaks when the store is no longer used.
Use readable stores for values that change automatically, like timers or external data sources.