Skip to content

Commit

Permalink
Add section to setAttributes documentation about immutability of attr…
Browse files Browse the repository at this point in the history
…ibutes (#12811)

* Add section to setAttributes documentation about immutability of attributes

* Simplify explanation of immutable attributes

* Fix typo and add link to redux's immutability docs

Co-Authored-By: talldan <[email protected]>
  • Loading branch information
talldan and talldan committed Dec 19, 2018
1 parent 92e3942 commit 5dba988
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions docs/designers-developers/developers/block-api/block-edit-save.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,24 @@ edit( { attributes, setAttributes, className, isSelected } ) {
}
```

When using attributes that are objects or arrays it's a good idea to copy or clone the attribute prior to updating it:

```js
// Good - here a new array is created from the old list attribute and a new list item:
const { list } = attributes;
const addListItem = ( newListItem ) => setAttributes( { list: [ ...list, newListItem ] } );

// Bad - here the list from the existing attribute is modified directly to add the new list item:
const { list } = attributes;
const addListItem = ( newListItem ) => {
list.push( newListItem );
setAttributes( { list } );
};

```

Why do this? In JavaScript, arrays and objects are passed by reference, so this practice ensures changes won't affect other code that might hold references to the same data. Furthermore, Gutenberg follows the philosophy of the Redux library that [state should be immutable](https://redux.js.org/faq/immutable-data#what-are-the-benefits-of-immutability)—data should not be changed directly, but instead a new version of the data created containing the changes.

## Save

The `save` function defines the way in which the different attributes should be combined into the final markup, which is then serialized by Gutenberg into `post_content`.
Expand Down

0 comments on commit 5dba988

Please sign in to comment.