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 $
.
import { writable } from 'svelte/store';
export const todos = writable([]);
<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} />