sveltesvelte-5

Svelte 5 form data not reactive in submit handler


I am trying to implement a form submit action in Svelte 5 but I am having some issues with reactivity it seems.

<script>
    const formData = $state({
        name: 'abc',
    })

    const saveData = (e) => {
        e.preventDefault()
        console.log(formData)
    }
</script>

<form onsubmit={saveData}>
    <input type="text" bind:value={formData.name}/>
    <button type="submit">
        Create
    </button>
</form>

<pre>
{formData.name}
</pre>

As expected, the {formData.name} displays the correct value, but the console.log(formData) always outputs abc no matter what I enter in the form. How would I retrieve the most recent value in the submit handler?


Solution

  • The $state proxies don't change the underlying object, they record changes on top of it, so if you log it you will see the proxy's target which is unchanged.

    There should even be a warning in the console, pointing you towards using $inspect or $state.snapshot to get the current value of the state.

    Your console.log contained $state proxies. Consider using $inspect(...) or $state.snapshot(...) instead

    For the most part, the proxy can be treated like any other object, e.g. if you want to JSON.stringify it to send it via fetch, that should work. But there are APIs and third party code which cannot deal with a proxy, in those cases one should pass a snapshot.