I'm working on a simple React shopping list where you can add/remove items from a list (pen here). It's working great so far except if you add a duplicate entry to the list and try and delete it, it gets confused (it's using the value as the key, so presumably that's why). To get around this I'd like to check if the value already exists in the list array when you add an item, and prevent it from being added. I've tried adding another check in the handleAddNew function by changing this: if (this.state.newItem.length > 0){
to this: if (this.state.newItem.length > 0 && this.state.items.includes(this.state.newItem) == false){
(line 18), but that doesn't seem to be working. Any ideas on how I should go about doing this?
I'm working on a simple React shopping list where you can add/remove items from a list (pen here). It's working great so far except if you add a duplicate entry to the list and try and delete it, it gets confused (it's using the value as the key, so presumably that's why). To get around this I'd like to check if the value already exists in the list array when you add an item, and prevent it from being added. I've tried adding another check in the handleAddNew function by changing this: if (this.state.newItem.length > 0){
to this: if (this.state.newItem.length > 0 && this.state.items.includes(this.state.newItem) == false){
(line 18), but that doesn't seem to be working. Any ideas on how I should go about doing this?
- Please post your code here, not behind an external link. – Colin Ricardo Commented Apr 1, 2019 at 12:36
- try by using some() ,it will work array.some(function(o){return o["key1"] === "value2";}) will be true if pair is found, otherwise false. – Kishan Jaiswal Commented Apr 1, 2019 at 12:38
-
1
if (this.state.newItem.length && !this.state.items.includes(this.state.newItem))
you can use this – Narendra Chouhan Commented Apr 1, 2019 at 12:42 - Thanks @NarendraChouhan, this also worked as well as Matt Way's answer below. I prefer this answer as it doesn't remove the text input entry when you click 'add item'. – AJT Commented Apr 1, 2019 at 12:47
- my pleasure @Godge can you mark the answer as correct, if you feel my answer works for you i have posted the code below – Narendra Chouhan Commented Apr 1, 2019 at 12:53
1 Answer
Reset to default 7The problem is that the entry form doesn't have access to the list to do any parison. You can achieve your original thought by altering the addItem
function to:
addItem(item) {
// only add if the item doesn't exist in the list
if(this.state.items.indexOf(item) < 0){
this.setState((state) => ({
items: state.items.concat([item])
}))
}
}
Note that I use indexOf
here, but includes
is also fine. You can do the parison however you like.