1

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
mhk
  • 436
  • 6
  • 14

2 Answers2

0

Adding it here instead of comments, as it required a code example. @mhk Here I observed it.

const {useEffect, useState} = React

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 (
      <div>
        <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)} />
     </div>  
    )
  })
)
}

ReactDOM.render(<App />, document.getElementById("root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>
simbathesailor
  • 3,681
  • 2
  • 19
  • 30
  • Yup you are right, its working as expected, logging ONCE on EACH change in input, i have copy-pasted the App.js on an online ReactIDE and it was working as expected... but strangely on my local environment (http://localhost/3000), with EXACT same code the issue still exists, may be some configs are different ??? through after some testing i got that handleInputChange is called once but somehow when i add setInputFields() it start logging the string twice... – mhk Aug 31 '20 at 02:59
0

okay after hours of re-search , seems like its a universal issue, perhaps the better phrase for the issue would be "onChange even firing twice in react.js"

any ways, as i suspects there was something wrong (read it set) within the configs, as the following page rightly directed me this https://www.mmbyte.com/article/91391.html

it was the react.strictMode which was enabled by default, which was causing double render of the components...

as suggested in here as well: My React Component is rendering twice because of Strict Mode

"StrictMode renders components twice (on dev but not production) in order to detect any problems with your code and warn you about them (which can be quite useful). If you have StrictMode enabled in your app but don't remember enabling it, it might be because you used create-react-app or similar to create your app initially, which automatically enables StrictMode by default."

I disabled strictMode in index.js and now double firing is stopped...

mhk
  • 436
  • 6
  • 14