Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating property of object within stored array - React Native

I am using react-native-simple-store and have written the below function to update the property of a supplied object stored in an array of objects. To do so, I used the method mentioned in issue #31 for deleting items.

Trouble is since I'm using .push, updating an item causes it to be rendered at the bottom of the array. This causes items to move in the FlatList unnecessarily.

Is there a more efficient method for updating a property of an object within the array (without causing this issue using .push)?

plusProgress = (itemId, progress) => {
  const foods = this.state.foods.filter(({ id }) => itemId !== id);
    const updatedItem = {
      itemId,
      progress: progress + 1
    };
  foods.push(updatedItem);
  this.setState({ foods });
  store.save('foods', foods);
}
like image 407
0xgareth Avatar asked Jan 28 '23 07:01

0xgareth


1 Answers

Create a new array with the updated object in the correct position, then call setState() with that new array. Be sure to return the current item as-is if is not the one you are trying to update. Otherwise, array elements will be replaced by null

  plusProgress = (itemId, progress) => {

  const foods = this.state.foods.map(item => {
    if (item.itemId === itemId) {
      return Object.assign({}, item, {progress: progress + 1});
    } 
    return item      
  })

  this.setState({ foods: foods })
}
like image 182
Wellington Cabral Avatar answered Feb 23 '23 22:02

Wellington Cabral