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);
}
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 })
}
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