Svelte logo

Svelte by Example: Writable Stores

A writable store is a value that can be subscribed to and updated. Runes handle most shared state needs, but stores are still useful when working with subscriptions or streams of data.

In this example, we'll move our todos into a writable store.

Svelte exposes a writable function to create writable stores.

Pass an initial value, and export the store for components to use.

stores.js
import { writable } from 'svelte/store';


export const todos = writable([
  { task: 'Walk dog', completed: false },
]);

This module-level store is shared by its importers. For per-user state on the server, create a store per component tree and share it through context instead.

Our AddTodo component calls its onadd prop with { task, completed: false }. Our Todo component receives task and completed, and calls onchecked with a boolean when its checkbox changes. These are callback props, not custom events.

update receives the current value. Always return the next value from its callback.

Return a new array to change the completed state of one todo.

Prefix a store name with $ to read its value. Svelte subscribes to the store and unsubscribes when the component is removed.

TodoList.svelte
<script>
  import Todo from './Todo.svelte';
  import AddTodo from './AddTodo.svelte';
  import { todos } from './stores.js';

  function addTodo(todo) {
    todos.update((items) => [...items, todo]);
  }



  function checkTodo(index, completed) {
    todos.update((items) => items.map((todo, i) =>
      i === index ? { ...todo, completed } : todo,
    ));
  }
</script>



{#each $todos as todo, index}
  <Todo
    {...todo}
    onchecked={(completed) => checkTodo(index, completed)}
  />
{/each}

<AddTodo onadd={addTodo} />

Use set to replace the entire store value. Here, we'll clear the list.

todos.set([]);