Skip to content

[Svelte5] A new rune to create state from a $props() value #13101

Open
@fsoft72

Description

@fsoft72

Describe the problem

Introduction

Sometimes you have a $state() obj Proxy object that you want to pass to other components, you want the user to be able to modify its contents, but you don't want to let the user modify the original obj, but to work on a copy of that.
For example, it could be a complex user profile obj, you want someone to edit, but you want to update the original only when the user confirms by clicking some buttons.

Current issues

  • Also, at the moment, passing a Proxy obj as a component prop, passes the original Proxy (and this could lead to some strange errors)
  • Furthermore, creating a new $state() from a Proxy obj, simply copies the original Proxy references to the new $state() obj and this is counter-intuitive (at least for me)

Available solution

If I am not mistaken everything, the only way to be sure to have a local $state() obj, from a Proxy obj passed as prop, is this:

let data = $state( $state.snapshot( proxyObj ) );

But this is a lot of code and also a bit convoluted to be a Svelte snippet.

Proposal

What I am proposing is the introduction of a new rune, similar to $bindable() that creates a local Proxy object by snapshotting the props parameter, something similar to:

let {
  data = $state.copy(),
  x,
  y
}: Props = $props()

I don't really like the $state.copy() name, but I think you get the idea.

More stuff

I have also created a small REPL with an example of how passing the a Proxy obj around, with three different approaches:

  • The Bad component is using the passed Proxy obj the wrong way
  • The Erroneous component is what I think a new $state() should do inside a component, but it just copies the Proxies
  • The Good component works, but it shows how convoluted this solution is for being Svelte

You can see the REPL here: Passing Props

Describe the proposed solution

For a clear and concise solution, it would be great to have a $bindable() like rune that hides the dirty nitty-gritty specs to the developer.

This scenario is bad:

let {  data: _data }: Props = $props();
let data = $state ( $state.snapshot ( _data ) );

This is far better:

let { data = $state.copy() }: Props = $props();

Also, I think that (maybe) everything passed to a component in props should be $state.snapshot() automatically.

Importance

nice to have

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