jasonmerino / react-native-simple-store

A minimalistic wrapper around React Native's AsyncStorage.

Home Page:https://www.npmjs.com/package/react-native-simple-store

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Updating property of object within stored array

ga-reth opened this issue · comments

I have written the below function to update the property of a supplied object stored in an array. To do so, I used the method mentioned in #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);
}

Thanks.

For others reference, I used the below method:

plusProgress = (foodId, progress) => {
 let foods = this.state.foods.map(item => {
   if (item.id === foodId) {
     return Object.assign({}, item, { progress: progress + 1 });
   }
   return item;
 });
 this.setState({ foods });
 store.save('foods', foods);
}

Rather than removing and re-inserting, this method assigns the object a new value.

Glad you were able to come up with a solution of this. As you suspected there is no built in functionality to do this sort of thing.