Reputation: 395
I have a page where users can submit forms. They can choose to add new forms to the page(form 2, 3, 4, 5 of the same form type).
I handle that through:
handleAddPastMainData() {
const pastMainData = this.state.mainData[0].pastMainData;
this.setState({
mainData: {
...this.state.mainData,
pastMainData: pastMainData.push([])
}
})
}
Then I map through pastMainData to display the added form.
What I am having a challenge with is with the handler for saving the data since the form is nested.
My current state is like this:
this.state = {
mainData: [
{pastMainData: []},
]
};
And my handler is:
handleMainInputChange = (event) => {
const name = event.target.name;
const value = target.type === 'checkbox' ? target.checked : target.value;
this.setState(state => {
state.mainData[0].pastMainData[name] = value;
return state
})
};
A sample form input field in my app is:
<Field
label="Main name"
id="pastMainName"
name="pastMainName"
placeholder="Super Awesome FName"
value={state.MainData[0].pastMainData.pastMainName}
onChange={handleMainInputChange}
/>
I assign a key to each form when I map through pastMainData.
So a user can choose to add more than 5 of the above field input and submit.
When the data is submitted, I want the state to look like this:
this.state = {
mainData: [
{pastMainData: [[field1], [field2], [field3]},
]
};
When the user returns, this gives me the option to check number of fields/forms the user has already completed and render them with the saved data.
However, this obviously is not working. Any way to improve my code and make it more efficient will be very appreciated.
Thanks
Upvotes: 0
Views: 2247
Reputation: 2080
Currently when I run the code, on clicking Add Form, it renders the form but continues to the next page. The call to continue to the next page is only on the handleSubmit method.
To stop it from continuing to the next page you probably need to e.preventDefault()
on that button.
"since the forms are multiple, how do I get the key and use that particular key in the handleMainInputChange."
Add the key to the Field, or Form. For example:
<Field
key={key}
label="Main name"
id="pastMainName"
name="pastMainName"
placeholder="Super Awesome FName"
value={state.MainData[0].pastMainData.pastMainName}
onChange={handleMainInputChange}
/>
And you should be able to access it like you would any data-attr, if not, you can pass it as a a param to the onChange
function.
also, maybe it would be easier to work with a different data structure for your state obj:
this.state = {
forms: {
form1: {},
form2: {},
form3: {},
}
};
may make setting and accessing easier in the long run.
Upvotes: 1