I have array selectedItems
and when I try to update existing object:
i.e. [{lable: "one", uniqueId: 1}, {lable: "two", uniqueId: 1}]
to:
i.e. [{lable: "one", uniqueId: 1}, {lable: "two", uniqueId: 3}]
It replaces the whole array with:
[ { lable: "two", uniqueId: 3 }]
how can I avoid that?
handleChange = (label, uniqueId) => {
const { selectedItems } = this.state
const findExistingItem = selectedItems.find((item) => {
return item.uniqueId === uniqueId;
})
if(findExistingItem) {
selectedItems.splice(findExistingItem);
this.setState(state => ({
selectedItems: [...state.selectedItems, {
label, uniqueId
}]
}))
} else {
this.setState(state => ({
selectedItems: [...state.selectedItems, {
label, uniqueId
}]
}))
}
}
Another approach would be to use the Array#filter
and Array#concat
functions in tandem, where;
uniqueId
are filtered. This substitutes the find()
logic of your current solution followed by,concat()
method being called to append the new "replacement item" to the end of the filtered arrayIn code that could be achieved like this:
handleChange = (label, uniqueId) => {
const {
selectedItems
} = this.state
this.setState({
selectedItems : selectedItems
/* Filter any existing item matching on uniqueId */
.filter(item => (item.uniqueId !== uniqueId))
/* Append replacement { label, uniqueId } to state array */
.concat([ { label, uniqueId } ])
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With