Quantcast
Channel: Active questions tagged svelte - Stack Overflow
Viewing all articles
Browse latest Browse all 1882

Nested reactivity with Svelte $derived

$
0
0

I'm making a swimming app and I want a button that adds an event to a swim meet. In place of a store, I'm using an object called STATE that acts as a single source of truth for the entire app.

<script>    import Event from '@shared/models/Event';    import { STATE, addEventToMeet } from '@src/state/state.svelte.js';    import EventEditor from './EventEditor.svelte';    let meet = $state(STATE.meet);    let events = $derived(STATE.meet.events);    let lastEvent = events[events.length - 1];    let name = $derived(STATE.meet.name);    function addEvent(eventData=lastEvent) {        console.log("Adding event", eventData);        let newEvent = new Event({            ...eventData,            n: (eventData?.n || 0) + 1,        });        addEventToMeet(newEvent);        events = [...events, newEvent]; // Why is this necessary?        console.log(STATE.meet.events, events);    }</script><div>    {name}<div class = 'events'>        {#each events as event (event.key)}<EventEditor {event} />        {/each}<button class = 'sb tool new-event'            onclick={() => addEvent()}>+ New Event</button></div></div>

For some reason, I can only get the list of events to update reactively with the line events = [...events, newEvent]. But I thought the whole point of Svelte 5 deep reactivity was that I could just reassign STATE.meet.events and it would automatically update. For reference, here is addEventToMeet

export function addEventToMeet(newEvent) {    STATE.meet.events = [...STATE.meet.events, newEvent];}

I tried the above without reassigning events, and what happens is that both STATE.meet.events is updated, but events is not updated unless I reload the component. I was expecting events to update reactively since it is $derived from STATE.meet.events.


Viewing all articles
Browse latest Browse all 1882

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>