Svelte logo

Svelte by Example: Custom Stores

The only requirement for an object to be a store is to expose a subscribe function. We can use Svelte's built-in store helpers to create custom stores. Custom stores are useful to encapsulate data and expose specific functions to manage state.

In this example, we'll create a custom todos store.

You can use a writable Svelte store as a starting point.

Functions the custom store should expose are implemented.

The functions and subscribe are exported. A Svelte store must export a subscribe function.

The store can be destructured for easy method access in the template.

The store can be used in the template like any other store, and $ calls subscribe.

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

const { update, set, subscribe } = writable([]);

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

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


export {
  addTodo,
  checkTodo,
  subscribe,
};
TodoList.svelte
<script>
  import Todo from './Todo.svelte';
  import AddTodo from './AddTodo.svelte';
  import { todos } from './stores.js';

  const { addTodo, checkTodo } = todos;

  addTodo('Walk dog');
</script>

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

<AddTodo on:add={addTodo} />