forked from ngxs/store
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
53 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
) | ||
) | ||
); | ||
} | ||
``` |