From 2dd8523d11bdbf6fdc26f313a1bef0f38724e1c9 Mon Sep 17 00:00:00 2001 From: Joaquin Cid Date: Mon, 28 Jun 2021 07:30:40 -0300 Subject: [PATCH] docs: snippets --- docs/SUMMARY.md | 2 ++ docs/advanced/operators.md | 4 ++++ docs/snippets/operators.md | 47 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 53 insertions(+) create mode 100644 docs/snippets/operators.md diff --git a/docs/SUMMARY.md b/docs/SUMMARY.md index eb8c37b52..08d2ebe0b 100644 --- a/docs/SUMMARY.md +++ b/docs/SUMMARY.md @@ -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) diff --git a/docs/advanced/operators.md b/docs/advanced/operators.md index 96c6ad12a..8079aca2c 100644 --- a/docs/advanced/operators.md +++ b/docs/advanced/operators.md @@ -224,6 +224,10 @@ function addEntity(entity: Entity): StateOperator { 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) diff --git a/docs/snippets/operators.md b/docs/snippets/operators.md new file mode 100644 index 000000000..f5672b61f --- /dev/null +++ b/docs/snippets/operators.md @@ -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({ + foods: upsertItem(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( + selector: number | Predicate, + upsertValue: T +): StateOperator { + return compose( + items => (items || []), + iif( + items => Number(selector) === selector, + iif( + items => selector < items.length, + >updateItem(selector, patch(upsertValue)), + >insertItem(upsertValue, selector) + ), + iif( + items => items.some(selector), + >updateItem(selector, patch(upsertValue)), + >insertItem(upsertValue) + ) + ) + ); +} +```