The below code is working as it should, I'm just trying to gain a better understanding of why.
How is the getCurrentElement
method of TestState
reactive without the use of $derived()
? Are store methods that make use of state reactive by default?
Im using svelte@5.0.0-next.217
test-store.svelte.ts
import { getContext, setContext } from 'svelte';class TestState { elements = [ { id: 'hghxt', name: 'Give', }, { id: 'vhtl9', name: 'Connection', }, { id: '5n0t0', name: 'Take notice', }, { id: 'xlfba', name: 'Keep learning', }, { id: '1f3z2', name: 'Be active', }, ]; #currentElementId = $state<string>(); getCurrentElement() { return this.elements.find(element => element.id === this.#currentElementId); } setCurrentElement(id: string) { if (!this.elements.some(element => element.id === id)) return; this.#currentElementId = id; }}const TEST_STORE_KEY = Symbol('TEST_STORE');export function setTestState() { return setContext(TEST_STORE_KEY, new TestState());}export function getTestState() { return getContext<ReturnType<typeof setTestState>>(TEST_STORE_KEY);}
TestComponent.svelte
<script lang="ts"> import { getTestState } from '$lib/stores/test-store.svelte'; // initialised at +page.svelte const testState = getTestState();</script>{#each testState.elements as { name, id }}<button class:bg-yellow={testState.getCurrentElement()?.id === id} onclick={() => testState.setCurrentElement(id)}> {name}</button>{/each}