svelte icon indicating copy to clipboard operation
svelte copied to clipboard

`$derived.by` not working as expected outside Svelte components

Open egilsster opened this issue 1 year ago • 2 comments

Describe the bug

I am migrating a medium-sized app that uses stores quite heavily to Svelte 5. I've got a few stores that rely on a search filter and I expect to get a fresh list of items based on the value in the filter store. This appears to work fine when its all done within the component, however, once the logic is extracted into a store, the derived.by that uses the items + filter does not re-run when the filter value changes.

Reproduction

I've put up a reproduction here: https://github.com/egilsster/runes-repro – notes with steps to reproduce are in the README.

Logs

No response

System Info

System:
    OS: macOS 14.4.1
    CPU: (12) arm64 Apple M2 Max
    Memory: 221.31 MB / 64.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 20.11.1 - /opt/homebrew/bin/node
    Yarn: 1.22.22 - /opt/homebrew/bin/yarn
    npm: 10.2.4 - /opt/homebrew/bin/npm
    pnpm: 9.4.0 - ~/Library/pnpm/pnpm
    bun: 1.1.7 - ~/.bun/bin/bun
  Browsers:
    Chrome: 126.0.6478.115
    Safari: 17.4.1
    Firefox: 127.0.1
  npmPackages:
    svelte: 5.0.0-next.162 => 5.0.0-next.162 
    webpack: ^5.92.1 => 5.92.1

Severity

blocking an upgrade

egilsster avatar Jun 21 '24 13:06 egilsster

https://github.com/egilsster/runes-repro/blob/aeed5e758a8cd639f0ad84b2c854194d3f306fd4/src/item-store.svelte.ts#L32C9-L40

filteredItems must be in closure as well:

return {
  get filteredItems() { return filteredItems; },
};

7nik avatar Jun 21 '24 18:06 7nik

Bingo, that plus I had to move the filter inside the scope of the derived callback. Thank you!

I wonder if there's something the compiler can warn about in these situations.

egilsster avatar Jun 22 '24 10:06 egilsster