How do i replace an element(object) in this.state.items array with the content of this.state.dataEdited . All of which is supposed to happen in the handleEditUpdate method
This.state
this.state = {
name: '',
day: '',
dob: '',
items : [],
currentItem: {},
dataEdited: {},
toggle: false,
loading: false
}
I tried this in handleEditUpdate Method although its wrong and did not produce desired result but there was no major error(except that i mutated state directly)
handleEditUpdate(event){
event.preventDefault();
const item = this.state.currentItem;
let index = this.state.items.indexOf(item)
if (~index){
this.setState({
items: this.state.items[index] = this.state.dataEdited
});
}
this.setState({ toggle: false })
}
handleEdit method
handleEdit(key){
this.setState({
currentItem: {...this.state.items[key]},
toggle: true
});
}
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.state.items.map((item, key) => (
<li key={key}>
<span> {item.name} </span>
<span> {item.day} </span>
<span> {item.dob} </span>
<button
className="btn btn-light"
onClick={() => this.handleEdit(key)} >edit</button>
<button
className="btn btn-danger"
onClick={() => this.handleDelete(key)}>delete</button>
</li>
I think your trying to achieve this? demo
you need to split previous state.items
before setting the new element, otherwise it will override by new item/s.
Adding
handleEditUpdate(event){
event.preventDefault();
const item = this.state.currentItem;
let index = this.state.items.indexOf(item)
if (~index){
this.setState({
items: [...this.state.items, this.state.dataEdited]
});
}
}
this.setState({ toggle: false })
}
Replacing
...
if (~index){
this.setState({
items: [this.state.dataEdited]
});
}
}
...
Removing
...
if (~index){
this.setState({
items: this.state.items.filter(i => i === ...)
});
}
}
...
I was able to achieve this using this code
handleUpdate(event){
event.preventDefault();
//const {name,day,dob} = this.state.dataEdited;
const item = this.state.currentItem;
let index = this.state.items.indexOf(item);
const newItemList = [...this.state.items];
newItemList.splice(index, 1, this.state.dataEdited);
this.setState({
items: [...newItemList],
toggle: false
})
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.