The state variable of index.js is changing automatically even without setState()
.
I was trying to make a form with submit and reset button. I needed the initial value of the state to reset the form. The initial value is in variable data. But when I edit form both state and data variable is changing
class User extends Component {
state = {
formData: data
}
updateForm = (newerState) =>{
console.log(this.state);
console.log(data);
}
submitform =(event)=>{
event.preventDefault();
let dataToSubmit = {};
for(let key in this.state.formData){
dataToSubmit[key]=this.state.formData[key].value;
}
}
resetForm =()=>{
console.log(data);
this.setState({formData: data});
}
render(){
return(
<div>
<form onSubmit={this.submitform}>
<FormFields
formData= {this.state.formData}
change={(newerState)=>this.updateForm(newerState)}
/>
<button type='submit'>Submit</button>
<button type='button' onClick={this.resetForm}>Reset</button>
</form>
</div>
)
}
}
I excepted: console.log(this.state); //user.js:12 console.log(data); //user.js:13
will output initial values of data.json but the output is
{element: "input", value: "ans", label: true, labeltext: "Ques1", config: {…}}
1: {element: "input", value: "ans", label: true, labeltext: "Ques2", config: {…}}
2: {element: "input", value: "ans", label: true, labeltext: "Ques3", config: {…}}
if I click backspace in all input field. 1,2,3 is deleted from data.value