Home > Back-end >  Prevent Item with same ID React Native
Prevent Item with same ID React Native

Time:06-06

I have this Array of Objects

Format =>

[{
  "id": "0.625240011345925",
  "item_name": "Item 23",
  "item_price": "23",
  "item_qty": "1"
}, {
  "id": "0.735657461482515",
  "item_name": "Item 4",
  "item_price": "30",
  "item_qty": "1"
}, {
  "id": "0.287635530963835",
  "item_name": "Item 2",
  "item_price": "56",
  "item_qty": "1"
}]

State

const [items, setItems] = React.useState([]);

Function which adds items in the State

const AddItemToBill = (navigation) => {
    navigation.navigate('AddItemToBill', {
        onReturn: (itemArray) => {
            const array = itemArray;
            const newState = [];
            for (let i = 0; i < array.length; i  ) {
                const element = array[i];
                newState.push(element);
            }
            setItems([...items, ...newState]);
        }, navigation
    })
};

Warning: Encountered two children with the same key, 0.625240011345925. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.

So My Question is that How can i check if the item with same id already exists & prevent it from adding into Array

CodePudding user response:

Try something like this:

(itemArray) => {
  const array = itemArray;
  const arrayOfIds = items.map(el => el.id);
  const newState = [];
  for (let i = 0; i < array.length; i  ) {
    const element = array[i];
    if (!arrayOfIds.includes(element.id)) {
      newState.push(element);
    }
  }
  setItems([...items, ...newState]);
}

CodePudding user response:

You can find the items with unique id using the below

const unique = [...new Map(itemArray.map(item => [item['id'], item])).values()];
  • Related