# 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.

## 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)
      )
    )
  );
}
```

### Collaborate with your awesome operator!

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](https://github.com/ngxs/store/issues/926) and submit your PR with your operator as part of the *Snippets* section.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.ngxs.io/v3.7/snippets/operators.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
