Skip to content

Svelte 5 $derived Variable Not Updating Reactively When Using update function on a Writable Store with Map() Value #15152

@jobayer977

Description

@jobayer977

Describe the bug

When using Svelte 5’s $derived variable to track a writable store that holds a Map(), the derived data does not update reactively when calling update on the store. However, if the store is explicitly set with a new Map(), the update is reflected correctly.

Expected Behavior

Calling testStore.update() should trigger reactivity in $derived($testStore) and update the UI accordingly.

Actual Behavior

  • Updating a Map() entry inside update() does not trigger a reactive update in $derived($testStore).
  • However, replacing the entire store with a new Map() using set(new Map([...])) works as expected.

Steps to Reproduce https://svelte.dev/playground/162b7af5885d49338694a65b3741a8ef?version=5.19.5

  1. Initialize a writable store as new Map().
  2. Create a $derived($testStore) variable to track the store’s state.
  3. Call testStore.update() to modify an entry in the Map().
  4. Observe that $derived($testStore) does not update.
  5. Use testStore.set(new Map([...])) instead, and observe that it works as expected.

Code Example

import { writable } from "svelte/store";

export const testStore = writable(new Map());
<script>
  import { testStore } from "./store";

  let testStoreInfo = $derived($testStore);

  $effect(() => {
    console.log({ testStore: testStoreInfo });
  });

  const onUpdateTestStore = (id) => {
    testStore.update((v) => {
      const values = v.get(id);
      v.set(id, values + id);
      return v;
    });

    // Works when setting a new Map instance
    // testStore.set(new Map([[id, Math.random()]]));
  };
</script>

<button onclick={() => onUpdateTestStore(1)}>
  Value - {JSON.stringify(testStoreInfo.get(1))}
</button>

Environment

  • Svelte Version: "svelte": "^5.0.0", (latest beta)
  • Browser: (e.g., Chrome, Firefox)
  • OS: (e.g., macOS)

Reproduction

https://svelte.dev/playground/162b7af5885d49338694a65b3741a8ef?version=5.19.5

Logs

System Info

System:
    OS: macOS 15.0.1
    CPU: (8) arm64 Apple M1 Pro
    Memory: 115.83 MB / 16.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 20.10.0 - ~/.nvm/versions/node/v20.10.0/bin/node
    Yarn: 1.22.22 - ~/.nvm/versions/node/v20.10.0/bin/yarn
    npm: 10.2.3 - ~/.nvm/versions/node/v20.10.0/bin/npm
    pnpm: 8.14.1 - ~/.nvm/versions/node/v20.10.0/bin/pnpm
    Watchman: 2024.12.02.00 - /opt/homebrew/bin/watchman
  Browsers:
    Brave Browser: 132.1.74.48
    Chrome: 132.0.6834.111
    Edge: 132.0.2957.127
    Safari: 18.0.1
  npmPackages:
    svelte: ^5.0.0 => 5.19.2

Severity

blocking updating

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions