I'm building a simple form, inputFields is basically the state; which is an array of object with inputs and handleInputChange calls the setInputsFields which updates the state... you see i have a adult:true property, im using checkbox in html form to update this field...
The issue: on initial load of app i observe that handleInputChange is executed once (handleInputChange called logged once), then after each change in any of input this functions executes twice (handleInputChange called logged 3, 5, 7 and so on) ... apart from the fact that it negates the logic of how i update the adult:true or false state, why the handleInputChange function is being executed twice...
export default function App() {
const [inputFields, setInputFields] = useState(()=>{
return [{ userName:'', age: 0, adult: true}]
})
const handleInputChange = ({name, value, type}, index) => {
setInputFields( prevInputField => {
if(type === "checkbox"){
console.log('handleInputChange called')
prevInputField[index][name]=!prevInputField[index][name]
} else{
console.log('handleInputChange called')
prevInputField[index][name]= value
}
return [...prevInputField]
})
}
return(
inputFields.map((inputField,index,inputFields)=> {
return (
<>
<input type="text" id="userName" name="userName" value={inputField.userName} onChange={(event)=> handleInputChange(event.target,index)} />
<input type="number" id="age" name="age" value={inputField.age} onChange={(event)=> handleInputChange(event.target,index)} />
<input type="checkbox" id="adult" value={inputField.adult} name="adult" defaultChecked={ inputField.adult ? true : false } onClick={(event)=> handleInputChange(event.target,index)} />
</>
)
})
)//ends return
}// ends App