Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

how to derive a deeply reactive variable from another?#16187

Answeredbybrunnerh
aster-void asked this question inQ&A
Discussion options

let's say I have a list of items

const list = $state([{ val: 1 }, { val: 2 }, { val: 3}]);

and I want adeeply reactive variable that's derived from it. it must:

  • cause an update when I mutate it.
  • reset if the original variable changes.

the only way I currently know is using$effect.

function double(item) {  return { val: item.val * 2 }}// workslet doubled = $state(list.map(double));$effect(() => {  doubled = list.map(double);});

$derived doesn't make the variabledeeply reactive, so it does not work:

https://svelte.dev/playground/5f8a2ab8ce1d4834a5ba16fce64fada6?version=latest

// not deeply reactiveconst doubled = $derived(list.map(double));
You must be logged in to vote

As has been mentioned in#16189, one can wrap the value in a$state proxy to get deep reactivity in derived values.

$derived.by(()=>{letval=$state(...);returnval;});
functionproxify(value){constproxified=$state(value);returnproxified;}letfoo=$derived(proxify(...));

Replies: 2 comments 3 replies

Comment options

As of Svelte 5.25.0, you can update deriveds and it just works:
https://svelte.dev/playground/94c9f7bf8eb14e328949dc055fb56795?version=5.34.3

You must be logged in to vote
3 replies
@aster-void
Comment options

it's not deeply reactive though:
https://svelte.dev/docs/svelte/$derived#Deriveds-and-reactivity

edit: nevermind the playground seems to be reactive

@peterreeves
Comment options

Huh, this was not behaviour I was expecting though. Maybe you're right?
https://svelte.dev/playground/5f8a2ab8ce1d4834a5ba16fce64fada6?version=latest

@aster-void
Comment options

Thanks, that was my mis-conclusion. I updated the title to have the word "deeply".

Comment options

As has been mentioned in#16189, one can wrap the value in a$state proxy to get deep reactivity in derived values.

$derived.by(()=>{letval=$state(...);returnval;});
functionproxify(value){constproxified=$state(value);returnproxified;}letfoo=$derived(proxify(...));
You must be logged in to vote
0 replies
Answer selected byaster-void
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Category
Q&A
Labels
None yet
3 participants
@aster-void@brunnerh@peterreeves

[8]ページ先頭

©2009-2025 Movatter.jp