Trying to log the values of name, day and dob elements stored in dataEdited as object.Two of the elements display Undefined with just one displaying the correct value. Here is the code
/* two-way state binding */ dataChange(event){ const target = event.target; const value = target.value; //gets value of the textbox const name = target.name; this.setState({ dataEdited: {[name]: value} }); } handleUpdate(event){ event.preventDefault(); const {name,day,dob} = this.state.dataEdited; console.log(name, day, dob); /* this.setState({ toggle: false }) */ } State
this.state = { name: '', day: '', dob: '', items : [], currentItem: {}, dataEdited: {}, toggle: false, loading: false } Render
<form onSubmit={this.handleUpdate}> <input className="" name="name" onChange={this.dataChange} defaultValue={this.state.currentItem.name} placeholder= "Celebrant's Name" ref={name => this.name = name} required /> <input className="" type="number" name="day" min="1" max="31" ref={day => this.day = day} onChange={this.dataChange} defaultValue={this.state.currentItem.day} placeholder= "day" /> <input className="" name="dob" type="month" onChange={this.dataChange} defaultValue={this.state.currentItem.dob} /> <button type="submit">update</button> <button onClick={this.handleEditCancel}>cancel</button> </form> This is the result on the console
undefined undefined "2020-08" I don't understand how this is possible, can I get an explanation. Also, how can I fix this?
renderfunction codethis.setStatecodesetState({ dataEdited: {[name]: value} }). You're settingdataEditedas an object that only has a single property. React only performs a shallow merge (Object.assign) when setting state, so if you redefine a state value that is an object, you have to spread the old value into the new one.