Svelte logo

Svelte by Example: Writable Stores

Stores are Svelte's way of managing state beyond local component state. A writable store is a store that can be written to and read from Svelte components.

In this example, we'll revisit our todo list example and refactor the internal component state to a writable store.

Svelte exposes a writable function to create writable stores.

Stores can be exported from a script to be accessible to your components. A store can have a default value set when it's initialized.

The value of a writable store can be set with set.

Alternatively, the value of a writable store can be updated with update and a callback. You can mutate the object to update the store state change in the update callback.

Or you can return a new object to update the store state.

The value of a store can be accessed by prefixing the store name with $.

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


export const todos = writable([]);
TodoList.svelte
<script>
  import Todo from './Todo.svelte';
  import AddTodo from './AddTodo.svelte';
  import { todos } from './stores.js';

  todos.set([
    {
      task: 'Walk dog',
      completed: false,
    },
  ]);

  function addTodo() {
    todos.update((todos) => {
      todos.push({
        task: 'Read newspaper',
        completed: false,
      });
    });
  }

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

{#each $todos as todo, index}
  <Todo
    {...todo}
    on:checked={(event) => {
      checkTodo(index, event.detail.checked);
    }}
  />
{/each}

<AddTodo on:add={addTodo} />