Arrays
Arrays in the State with useStore guide.
An array store is a store like any other. length, indices and the array methods are tracked through the view.
src/todo-list.tsxtsx
import { For } from "@shadow-js/web";
import { useStore } from "@shadow-js/core";
interface Todo {
id: number;
title: string;
done: boolean;
}
export function TodoList() {
const [todos, setTodos] = useStore<Todo[]>([{ id: 1, title: "buy milk", done: false }]);
const open = todos.filter((todo) => !todo.done).length;
return (
<div>
<For each={todos} key={(todo) => todo.id}>
{(todo) => <span>{todo().title}</span>}
</For>
<button
type="button"
onClick={() => setTodos((draft) => void draft.push({ id: draft.length + 1, title: "x", done: false }))}
>
add
</button>
<small>{open} open</small>
</div>
);
}
For an array held at the root, the draft may return a new array and the result is reconciled by id (retained items keep their identity):
Lists are covered in Lists and keys.