I’ve got the following component:
<script>
export let componentID;
console.log("component iD", componentID)
</script>
<div>
<div class="grid grid-cols-1 gap-x-6 gap-y-8 sm:grid-cols-6">
<div class="sm:col-span-3">
<label class="label">
<span class="label-text text-lg">Title</span>
</label>
<input type="text" name="track-title[][{componentID}]" class="input input-bordered input-lg w-full">
</div>
<div class="sm:col-span-1">
<label class="label">
<span class="label-text text-lg">Duration</span>
</label>
<input type="text" name="track-duration[][{componentID}]" class="input input-bordered input-lg w-full">
</div>
</div>
</div>
As you can see, this component contains only 2 input fields. I have the following route
(+page.svelte
) and what I want to do is to have multiple copies of the same component, something like this:
<script>
import TrackForm from "../../components/forms/TrackForm.svelte";
</script>
<form method="POST">
<TrackForm componentID="1" />
<br/>
<hr>
<br/>
<TrackForm componentID="2" />
<button type="submit" class="btn-primary btn-wide btn-info mt-10">Save</button>
</form>
Eventually, the components will be added dynamically using a button, for now, this is a proof of concept.
The action in +page.server.js
is not doing anything at the moment, just printing the submitted data:
export const actions = {
default: async ({ request }) => {
const data = Object.fromEntries(await request.formData());
console.log("data:", data);
return {}
}
}
When submitting the form I’m getting the following:
data: {
'track-title[][1]': 'aaaaa',
'track-duration[][1]': '111',
'track-title[][2]': 'vbbb',
'track-duration[][2]': '2222'
}
What I’m wondering is whether there’s a way to automatically get the data in a better format, say:
[
{
"track-title": 'aaaaa',
"track-duration": '111'
},
{
"track-title": 'vbbb',
"track-duration": '2222'
}
]
or a library that does that.