ciscoheat / sveltekit-superforms

Making SvelteKit forms a pleasure to use!
https://superforms.rocks
MIT License
2.26k stars 65 forks source link

updating a value in an each loop doesn't work under specific circumstances #509

Closed macmillen closed 1 week ago

macmillen commented 1 week ago

Here is my repro: https://www.sveltelab.dev/xo9hz1kbl8dq9l9

Description Somehow when binding to $form it doesn't have the correct form value inside the onUpdate fn.


<form use:enhance method="post">
    {#each $form.priceRules ?? [] as priceRule}
        <!-- this doesn't work (only when updating another form field afterwards: -->
        <PriceSelection bind:selectedItem={priceRule.priceCategory} />

        <!-- this works: -->
        <!-- <PriceSelection bind:selectedItem={$form.priceRules[0].priceCategory} /> -->
    {/each}

    <button type="submit">submit</button>
</form>
ciscoheat commented 1 week ago

Yes, you cannot bind to a loop variable as that breaks the bind reference. Use the direct reference instead, as in your working example.

ciscoheat commented 1 week ago

You'll need to use the index for the each loop like this:

{#each $form.priceRules ?? [] as _, i}
macmillen commented 1 week ago

In svelte 4 it worked though for some reason. Do you know why?

My problem is that I get a type error because if I do an array access [0] with noUncheckedIndexedAccess enabled it can be undefined and I can't bind to a value if it contains a [0]?. check

macmillen commented 1 week ago

I created a demo with the exact same components and files but with Svelte 4 and this time it works as expected. https://www.sveltelab.dev/ixggdu5xzb898md

Is it something that needs to be fixed or can't we do anything about it because of some Svelte 5 limitation?

macmillen commented 21 hours ago

@ciscoheat I'm sorry to bother again but we're in the middle of a Svelte 5 upgrade and can't proceed because of this issue.

  1. What I'm wondering about is that while the $form store is updating correctly and reactively the form param inside the onUpdate callback is not up to date

  2. This issue seems to only occur in Svelte 5, that's why it seems to me like a bug

  3. If I use the index to bind to the form (to solve the issue) I get a type error because if I do an array access [0] with noUncheckedIndexedAccess enabled it can be undefined and I can't bind to a value if it contains a [0]?. check

ciscoheat commented 19 hours ago

Creating a component that is used inside, or instead of, the each loop can be a way to make it work.