storeから`subscribe`を取り出し、`UserMap`に変更があったとき`state`に代入するようsubscribeする。メソッドやgetterはその`state`を使って処理する。
```ts:store.ts
import { writable } from "svelte/store";
export interface Human {
id: string;
name: string;
}
type HumanById = { [id: Human["id"]]: Human };
export const humanStore = (function () {
const { subscribe, ...rest } = writable<HumanById>({});
let state: HumanById;
subscribe((v) => {
state = v;
});
return {
subscribe,
...rest,
// getter
names: () => Object.values(state).map((x) => x.name),
// メソッド
exists: (state, id: string) => id in state,
};
})();
```
svelteファイルの方では、reactiveになるようにする。
- `
なしで呼び出す
- 第1引数に`
つきを指定する
```html:*.svelte
<!--getter-->
<div>{humanStore.names($humanStore)}</div>
<!--メソッド-->
<div>{humanStore.exists($humanStore, "3")}</div>
```
`$humanStore.names($humanStore)`はエラーになる。`humanStore.names()`はエラーにならないが、`humanStore`を更新しても画面が再描画されない。
## 参考
- [Store with getters • REPL • Svelte](https://svelte.dev/repl/2991d70689674f50a5fb3e30216d699e?version=3.24.1)