State Operators
In this section you will find state operators that are not part of the library but can be very helpful in your app.

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

foods: upsertItem<Food>(f => === foodId, food)

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 || []),
items => Number(selector) === selector,
items => selector < items.length,
<StateOperator<T[]>>updateItem(selector, patch(upsertValue)),
<StateOperator<T[]>>insertItem(upsertValue, <number>selector)
items => items.some(<any>selector),
<StateOperator<T[]>>updateItem(selector, patch(upsertValue)),

Have you identified an use case for a new operator? If that's the case you can collaborate sharing it here! To learn more read this issue and submit your PR with your operator as part of the Snippets section.
Last modified 1mo ago
Copy link
Edit on GitHub
On this page
State Operator Code
Collaborate with your awesome operator!