# Rules of Thumb pt2

## When to create actions?

* **Anytime we want to interact with the store or API**
* **No shortcuts**
* **Use classes for actions**
* **Use enums for action names**
* **Export actions types using a union type**
* **3 action approach - request, success, failure**
* **Consider Action Creators**

{% hint style="danger" %}
Single action that does everything - Anti Pattern
{% endhint %}

```
// Single action that does everything
export class UpdateUsers implements Action {
 readonly type = UserActionTypes.UpdateUsers;
 constructor(public payload: { users: User[] }) {}
}
```

## Sample Action

{% embed url="<https://stackblitz.com/edit/advanced-ngrx-0-rulesofthumb?file=src%2Fapp%2Fusers%2Factions%2Fuser.actions.ts&view=editor>" %}

## Related/Nested Data

* **Don’t do it**
* **Complicates reducers**
* **Easy to mutate store**
* **Prefer dictionaries vs arrays (NgRx Entity)**

## Maximize Selectors

**Use Selectors to filter/manipulate data from the store**

* **Supports parameters**
* **Memoized**
* **Release memoization**

## Service With a Subject

* **Most projects don’t need NgRx**
* **Simple pattern**
* **Works well with container/presenter**
* **Upgradable to NgRx**

### Service with a subject basics

* **Regular Angular service**
* **Private member variable of type BehaviorSubject**
* **Public get prop to access stream**
* **Service methods update stream**

{% embed url="<https://stackblitz.com/edit/tour-of-heroes-service-with-subject?file=src%2Fapp%2Fcore%2Fhero.service.ts&view=editor>" %}

## When NOT to use Service with a Subject?

* **Application or feature is complex**
* **Want to track state changes**
* **Recreate user errors**
* **Implement advanced logging**

{% hint style="info" %}
Refactor Tour of Heroes to use Service with a subject [https://stackblitz.com/github/jessesanders/tour-of-heroes/tree/**s**ervice-with-subject](https://stackblitz.com/github/jessesanders/tour-of-heroes/tree/container-presenter)
{% endhint %}


---

# 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://briebug.gitbook.io/ngrx-workshop/rules-of-thumb-pt2.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.
