I have the following component with a function which can dynamically add New elements in my form. I have a button and when clicking on the button, a new form field will be added. Now I need to keep this new field's value in a new state and send it to the API. To send all the new fields, I planned to set a single state as array and push new field values after enter them. After adding few new fields, I need something like this,
this.state.other [
{
description: "field 1 description",
amount: "120$"
},
{
description: "field 2 description",
amount: "180$"
},
{
description: "field 3 description",
amount: "156$"
},
]
This is what I have tried so far:
let dataId = 0;
class ClientIntakeModal extends Component {
constructor(props) {
super(props);
this.allOtherCosts = [];
this.state = {
otherCosts: this.allOtherCosts,
other: [],
}
this.otherDescInputHandle = this.otherDescInputHandle.bind(this);
}
appendData = () => {
dataId = dataId + 1;
this.allOtherCosts.push(
<div className="halfWidth jobCostMain" key={dataId}>
<div>
<div className="jobDescAdded">
<TextField
id={'costDescription'}
name={'description'}
type="text"
value={this.state.other.description}
onChange={this.otherDescInputHandle}
/>
</div>
<div className="jobCostAdded">
<TextField
id={'costAmount'}
name={'amount'}
type="number"
value={this.state.other.amount}
onChange={this.otherDescInputHandle}
/>
</div>
</div>
</div>
);
this.setState({
otherCosts: this.allOtherCosts
});
}
otherDescInputHandle(event) {
const target = event.target;
const value = target.value;
const name = target.name;
this.setState({
other: [
...this.state.other,
{
[name]:value
},
]
});
}
render() {
return(
<div>
<div id="addNewUser" className="addNewUser" onClick={this.appendData}>
<span>+</span>
</div>
{this.allOtherCosts}
</div>
)
}
}
The problem is, I'm receiving something like follows
this.state.other [
{
description: "f",
},
{
description: "fi",
},
{
description: "fie",
},
{
description: "fiel",
},
]
How can I get the correct state here?