How do I make the element and schema more reactive? I want the schema to be updated using the loadSchema function every time the element changes. Use svelte 5 runes.
To make schema more reactive to changes in element, you'll want to harness Svelte 5 Runes properly — the reactive primitives such as $effect, $derived, and $state.
The main issue here is this line:
ts
let element = $derived(store.elements.find(el => el.id === elementId));
This won't work correctly because you're calling .find(...) on a static array directly within the $derived without re-running whenever store or elementId change. The .find(...) isn’t being tracked reactively.
Let's fix that step-by-step in a clean and fully reactive way using Svelte 5 runes:
✅ Correct and Reactive Version
ts
import { $state, $derived, $effect } from 'svelte';
const { elementId } = $props<{ elementId: string }>();
const store = $derived(() => get(engineStore));
// Properly derive 'element' reactively from store + elementId
const element = $derived(() => {
const elements = store.elements;
return elements.find(el => el.id === elementId) ?? null;
});
// Now derive 'schema' from 'element'
const schema = $derived(() => {
if (element) {
return loadSchema(element.type, element.data?.components ?? []);
}
return null;
});
🔍 Why your original code wasn't reactive enough:
Problem 1 — Non-reactive access
ts
let element = $derived(store.elements.find(el => el.id === elementId));
Here, you're calling .find(...) outside of a reactive scope. You should instead wrap it in a lambda passed to $derived to track both store and elementId.
Problem 2 — Assumptions about reactivity
You're assuming element will update reactively when store or elementId changes — but unless you explicitly derive it from those sources, it won't react.
Use $derived(() => ...) to properly track dependent values like store, elementId, and element. Avoid accessing outside those functions or using values that might not be tracked reactively.
Let me know if you want to load the schema asynchronously or need to memoize schema loads based on the type/components.