Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Om4ar/ebdc8f3546e3d27b89f354edb5d1b52e to your computer and use it in GitHub Desktop.
Save Om4ar/ebdc8f3546e3d27b89f354edb5d1b52e to your computer and use it in GitHub Desktop.
immutable react update state cheat sheet
Immutable Update Cheat Sheet / Receipes
Objects
Updating object property
// Alternative #1
return {...originalObject, existingPropertyKey: newValue };
// Alternative #2
return Object.assign({}, originalObject, { existingPropertyKey: newValue }); // Notice extra { } around properties
Updating nested object property
For nested fields you need to remember to copy every level, read more here.
return {...originalObject, existingPropertyKey:
{...originalObject.existingPropertyKey, nestedProperty: newValue}
};
// Example: customer.address.street = 'My new street' becomes
// return {...customer, address: { ...address, street: 'My new street'} };
Arrays
Adding item
return [...array, newItem ];
Inserting item at index
return [
...array.slice(0, insertIndex),
newItem,
...array.slice(insertIndex)
];
Removing item at index
// Alternative #1
return [
...array.slice(0, removeIndex),
...array.slice(removeIndex + 1)
];
// Alternative #2
return array.filter((item, index) => index !== removeIndex);
Replacing item at index
return [
...array.slice(0, replacedItemIndex),
newItem,
...array.slice(replacedItemIndex + 1)
];
Updating item based on match
// Note: You will need to write your own isItemMatching(...) and updateItem(...) code
return array.map((currentItem, index) => {
if (isItemMatching(newItem, currentItem)) {
// Return an update copy, see object updating examples
return updateItem(newItem, currentItem); // ...or Object.assign(...) or {...currentItem, existingProperty: newValue} and so on
} else {
// Not the item we wan't to update just return the same
return currentItem;
}
});
Remove item based on match
// Note: You will need to write your own isItemToRemove(...) code
return array.filter((currentItem, index) => {
if (!isItemToRemove(newItem, currentItem)) {
// Not the item we want to remove so we keep it
return currentItem;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment