I have a rather tricky question to ask, I'm working on a page that accepts several inputs from the Data-Base and with that I'm generating several inputs( the number of inputs is not constant)
basically like this:
const form = this.state.inputs.map((input, i) => {
if (input) {
return (
<div key={i}>
<div>
<label htmlFor={input.inputLabel}>{input.inputName}</label>
</div>
<div className="form-input">
<input
name={`${input.inputName}-${i}`}
type={input.inputType}
id={input.inputLabel}
onChange={this.onChange}
/>
</div>
</div>
);
}
});
after generating the form with the unknown number of values ( depends on the Data-Base) I want to save all the values of that form, but because I do not know the number of inputs I made 2 arrays ( I need to save the value and the name to be later shown in a different page)
state = {
....
inputData: {
names: [],
values: []
}
....
};
but I'm having trouble of actually saving the values in the setState
onChange = e => {
e.preventDefault();
const { name, value } = e.target;
var nameIndex = name.split('-');
const names = [];
const values = [];
values[nameIndex[1]] = value;
names[nameIndex[1]] = nameIndex[0];
const inputData = { names, values };
this.setState({ inputData });
};
the setState works like this: on my map I give each input a name that contains the index that's generated by the map so the name is like "inputname-1", and I use split to take out the 1 and update the two arrays I did in the setState (values,names) and everytime the user writes in the input it changes the value inside the array like so: values[1]=(users input...) , but I noticed that if I change the 2nd value for example, the values before him in the index 1 and 0 become undefined, am I missing something?
const names = []; const values = [];doconst names = this.state.inputData.names; const values = this.state.inputData.valuesconsttovarit would be better