I have a functional React component with useState hooks, and I have an array with five textinput fields. The values of the input fields are registered in the state in an array. The problem is, that I want to update the inputfields array with an onChange listener every time I input something. However, once I load the page, the function (onChange listener) is executed immediately in an endless loop... why is that?
const addDublette = props => {
// constructor(props) {
// super(props);
// this.textInput1 = React.createRef();
// }
const [actualState, changeState] = useState({
showInputField: false,
dublettenIDs: [],
errorMessage: '',
inputFields: ['','','','',''],
}); ....
My method to update input values in state:
const handleDoublettenIDs = (event,index) => {
let idnumber = event.target.value;
let newInputFields = [...actualState.inputFields];
newInputFields.splice(index,1, idnumber);
console.log(newInputFields);
if (isNaN(idnumber)) {
changeState({...actualState, errorMessage: 'ID is not a number'})
} if (idnumber > 2147483647) {
changeState({...actualState, errorMessage: 'Number can not be bigger than 2147483647!'})
}
else {
changeState({...actualState, inputFields: newInputFields, errorMessage: '' });
}
}
My return render method:
return (
<p>
{
actualState.inputFields.map((val,index) => (
<InputElement key={index} elemValue = {val} name={"input" + index} onChangeListener={(event,index) => handleDoublettenIDs(event,index)} />
)
)
}
<p>{errorMessage}</p>
<br />
<p><button onClick = {handleInputs(props.anzeigeID)}>absenden</button></p>
</p> ...)
I pass the onChangeListener method down to my InputElement components "onChange" method with the props.onChangeListener property...
const inputElement = (props) => (
<p>
<input
value ={props.elemValue}
ref={props.reference}
name={props.name}
type="number"
max="2147483647"
placeholder="Doubletten-ID"
onChange={props.onChangeListener}>
</input>
</p>
)
export default inputElement
I think the problem could be in a circular update dependency loop, but I still have not found out where and how...