I'm Posting input data to API's where the API's structure as array list with n objects.
Problem: The problem I'm facing is while handling the change, i'm replacing the data instead of inserting as an another object.
My code as follows:
the objects in the list is dynamic not limited to two
in Constructor->
this.state={
formData: [
{
information: "",
from: "",
to: "",
},
{
information: "",
from: "",
to: "",
},
],
}
handling the Change as follow:
handleChange = (e) => {
const { name, value } = e.target;
const { formData} = this.state;
this.setState({
formData: {
...formData,
[name]: value,
},
});
Handle submit:
handleSubmit = (e) => {
e.preventDefault();
console.log(this.state.formData);
}
Form fields as follows:
<form onSubmit={this.handleSubmit}>
<div>
<input type="text" name="information" onChange={this.handleChange} />
<input type="text" name="from" onChange={this.handleChange} />
<input type="text" name="to" onChange={this.handleChange} />
</div>
<div>
<input type="text" name="information" onChange={this.handleChange} />
<input type="text" name="from" onChange={this.handleChange} />
<input type="text" name="to" onChange={this.handleChange} />
</div>
.
.
.
<button> + Add new Set (div) </button>
<button type="submit"> Submit </button>
</form>
I'm aware that mistake is handing logic but i tried lot to correct. Please help me out.
Edit: Expected output:
[
{
"information": "info 1",
"from": 1,
"to": 50
},
{
"information": "info 2",
"from": 51,
"to": 80
},
{
"information": "info 3",
"from": 81,
"to": 100
}
]