I have a page that has multiple form. The for register multiple users to one single endpoint. My Payload should look like this:
[
{username: "benjoe", address: "2, Salem Road, NA"},
{username: "carryme", address: "2, Benson Street, London"},
{username: "slowwy", address: "10, Salem Road, NA"},
{username: "samog", address: "90, Salem Murphy Way, QA"},
]
This is an example of a page with four forms. Please note that number of forms depend on the Number the user selected from a list.
I currently don’t know the method to use to handle this form as the whole form has same fields and names. I am to use one single onSubmit button to submit them.
I am thinking of using setState to manage the input states as I believe that useForm hook might not be useful here.
Sample of form is:
<div className="grid grid-cols-2 gap-5">
<CreateUserForm />
<CreateUserForm />
<CreateUserForm />
<CreateUserForm />
<Button>Submit</Button>
</div>
This is CreateUserForm
component:
<form>
<input name="username" placeholder="Enter Username" />
<input name="address" placeholder="Enter Address" />
</form>
How do I set the state as the array of objects at the top receiving the data from the different inputs from the multiple forms.
3
Not that it is an issue that you have multiple forms, but in this case I will suggest that you create one form with multiple fieldsets. Fieldsets are good for organizing a form, like in this case where you have repeating form fields that have the same name (more form field with the same name is not an issue btw.).
In the callback of the submit event you can iterate the fieldsets and create your array, and then you can use AJAX (I prefer the using the Fetch API) to send your data to some endpoint.
document.forms.form01.addEventListener('submit', e => {
e.preventDefault();
let data = [...e.target.elements.user].map(fieldset => {
return [...fieldset.elements].reduce((obj, input) => {
obj[input.name] = input.value;
return obj;
}, {});
});
console.log(data);
});
<form name="form01">
<fieldset name="user">
<input name="username" placeholder="Enter Username" />
<input name="address" placeholder="Enter Address" />
</fieldset>
<fieldset name="user">
<input name="username" placeholder="Enter Username" />
<input name="address" placeholder="Enter Address" />
</fieldset>
<button type="submit">Submit</button>
</form>