NgRx
NgRx is a library for managing state in Angular applications, inspired by Redux.
Installing NgRx - work in progress
To install NgRx, run the following command in your terminal:
npm install @ngrx/store
npm install @ngrx/effects
npm install @ngrx/store-devtools
When implementing state management with NgRx, we need to think about the following:
- Actions: describe unique events that are dispatched from components and services.
- Reducers: handle state transitions that are tied to actions.
- Effects: are used for complex side-effects, such as making HTTP requests or interacting with browser APIs.
- Selectors: are used for getting specific pieces of state from the store.
- Store: is a centralized state container that holds the application state.
Redux devtools
Redux devtools is a plugin for Chrome and Firefox that allows you to inspect the state of your application. It also allows you to travel back in time and replay actions. You can find it here.
Creating the store
To create the store, we need to import the StoreModule
from @ngrx/store
and pass it a reducer function. The reducer function is responsible for handling state transitions that are tied to actions.
Creating the reducer
A reducer is a pure function that takes the previous state and an action, and returns the next state. It is used to handle state transitions that are tied to actions.
- create state directory
- create actions, effects, reducers, selectors and state files
- in app.state.ts:
export interface AppState {
todos: string[];
}
export const initialState: AppState = {
todos: []
}
- for effects to work
EffectsModule.forRoot([MenusEffects]),