sveltejs / svelte

web development for the rest of us
https://svelte.dev
MIT License
79.83k stars 4.24k forks source link

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

Open fsoft72 opened 2 months ago

fsoft72 commented 2 months ago

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

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:

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

JLAcostaEC commented 2 months ago

I don't know where I read that using $bindable() would convert the prop into a $state() + sync, but it was from someone on the team, I don't know if it was just a discussion or an issue.

fsoft72 commented 2 months ago

I noticed I did a mistake in the Erroneous.svelte component. The data $state() should be:

    let { data: _data }: Props = $props();
    let data = $state(_data); // this is wrong, copies Proxy references

I have updated the REPL here