Skip to content

Commit

Permalink
docs: snippets
Browse files Browse the repository at this point in the history
  • Loading branch information
joaqcid authored Jun 28, 2021
1 parent e99e5ce commit 2dd8523
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
2 changes: 2 additions & 0 deletions docs/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@
- [Style Guide](recipes/style-guide.md)
- [Unit Testing](recipes/unit-testing.md)
- [RxAngular Integration](recipes/intregration-with-rxangular.md)
- Snippets
- [State Operators](snippets/operators.md)
- Plugins
- [Introduction](plugins/intro.md)
- [CLI](plugins/cli.md)
Expand Down
4 changes: 4 additions & 0 deletions docs/advanced/operators.md
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,10 @@ function addEntity(entity: Entity): StateOperator<EntitiesStateModel> {
As you can see, state operators are very powerful to start moving your immutable state updates to be more declarative and expressive. Enhancing the overall maintainability and readability of your state class code.
## Snippets
Check this [section]() for more operators that you can add to your application.
## Relevant Articles
[NGXS State Operators](https://medium.com/ngxs/ngxs-state-operators-8b339641b220)
47 changes: 47 additions & 0 deletions docs/snippets/operators.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# State Operators Snippets

In this section you will find state operators that didnt make it to the library but can be very helpful in your app.

## upsertItem

Inserts or updates an item in an array depending on whether it exists.

### Usage

```ts
ctx.setState(
patch<FoodModel>({
foods: upsertItem<Food>(f => f.id === foodId, food)
})
);
```

### State Operator Code

```ts
import { Predicate } from '@ngxs/store/operators/internals';
import { StateOperator } from '@ngxs/store';
import { compose, updateItem, iif, insertItem, patch } from '@ngxs/store/operators';

export function upsertItem<T>(
selector: number | Predicate<T>,
upsertValue: T
): StateOperator<T[]> {
return compose<T[]>(
items => <T[]>(items || []),
iif<T[]>(
items => Number(selector) === selector,
iif<T[]>(
items => selector < items.length,
<StateOperator<T[]>>updateItem(selector, patch(upsertValue)),
<StateOperator<T[]>>insertItem(upsertValue, <number>selector)
),
iif<T[]>(
items => items.some(<any>selector),
<StateOperator<T[]>>updateItem(selector, patch(upsertValue)),
<StateOperator<T[]>>insertItem(upsertValue)
)
)
);
}
```

0 comments on commit 2dd8523

Please sign in to comment.