ciscoheat / sveltekit-superforms

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

Snapshots with multiple forms #448

Closed Vpatel1093 closed 1 month ago

Vpatel1093 commented 2 months ago

Description I have a signup wizard that I've broken into a multi-step single page flow with shallow routing and different schemas per form (following https://superforms.rocks/concepts/multiple-forms) but haven't been able to use snapshots to preserve the state of all of the forms. I have tried exporting the capture and restore functions returned by superForm() both as an array and by using different variable names but the snapshot API seems to support one of each capture/restore function unless I missed something. Just wanted to see if anyone else has encountered this and found a way forward?

Edit: Don't think this is a bug, just a question but I can't change the label

If applicable, a MRE https://www.sveltelab.dev/a2uyglykqxn5dev

18thletter commented 1 month ago

Seems like maybe Sveltekit should have a way to handle multiple snapshots, but since snapshot is just an object and capture and restore are just functions, it is definitely possible.

I got this to work:

<script lang="ts">
  import { schema1, schema2 } from './schema'
  import SuperDebug, { superForm, type SuperFormSnapshot } from 'sveltekit-superforms'
  import { zodClient } from 'sveltekit-superforms/adapters'
  import { page } from '$app/stores'

  let data

  const form1 = superForm(data.form1, {
    validators: zodClient(schema1),
    dataType: 'json'
  })

  const form2 = superForm(data.form2, {
    validators: zodClient(schema2),
    dataType: 'json'
  })

  const { form: formData1, capture: capture1, restore: restore1 } = form1
  const { form: formData2, capture: capture2, restore: restore2 } = form2

  function multiRestore([form1Snapshot, form2Snapshot]: [
    form1Snapshot: SuperFormSnapshot<typeof $formData1>,
    form2Snapshot: SuperFormSnapshot<typeof $formData2>
  ]) {
    restore1(form1Snapshot)
    restore2(form2Snapshot)
  }

  function multiCapture() {
    return [
      capture1(),
      capture2()
    ]
  }

  const snapshot = { capture: multiCapture, restore: multiRestore }

  export { data, snapshot }
</script>