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
.
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,
};
<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} />