State Management using NGXS in Angular

Reading Time: 3 minutes

Why do we need State Management?

When creating a web application, one of the questions to ask is how data should be managed. The next question is how this could this be performant and reliable. The current trend is to use a Redux-based storage solution, which consists of a Store, Selectors to get data from the store in the form of Observables and Actions to modify the store. This allows for a single source of truth, a read-only state and the flow of data going in one direction.

Redux – State Management Tool

Redux was built for react. Since it was designed for React, it lacked the necessary plumbing to make it work well with Angular. For state management in Angular, NGRX is used. NgRx Store provides reactive state management for Angular apps inspired by Redux.

NGXS

NGXS is also a state management pattern + library for Angular. As NGXS is modeled after the CQRS pattern popularly implemented in libraries Redux and NGRX but reduces boilerplate by using modern TypesScript features such as classes and decorators.

There are 4 major concepts in NGXS:

  1. Store: The store is a global state manager that dispatches actions your state containers listen to and provides a way to select data slices out from the global state.
  2. Actions: Actions describe unique events that are dispatched from components and services. Each action contains a type field which is their unique identifier and payload required for that action.
  3. State: Class definition of the state. State changes are handled by pure functions also called reducers that take the current state and the latest action to compute a new state.
  4. Selects: Selectors are pure functions used to select, derive and compose pieces of state

These concepts create a circular control flow traveling from a component dispatching an action, to a store reacting to the action, back to the component through a state select.

Control Flow NGXS

NGXS Example

Actions:

Actions can either be thought of as a command which should trigger something to happen, or as the resulting event of something that has already happened. Each action contains a type field which is their unique identifier and payload for that action.

export interface ZebraFood {
  name: string;
  hay: number;
  carrots: number;
}
export class FeedZebra { 
    static readonly type = '[Zoo] Feed Zebra';  
    constructor(public zebraToFeed: ZebraFood) {}
}

In this action, zebra is feed with .This type of the action is triggered to feed the zebra with hay. The zebraToFeed field of the action class will represent the amount of food for the zebra we should feed.

State:

States are classes along with decorators to describe metadata and action mappings. A state definition is:

@State<string[]>({
  name: 'animals',
  defaults: {
    zebraFood: []
  }
})

In the state decorator, we have metadata for the state. The name property is used to state the name of state to slice. Name is a required parameter and must be the unique for the application. defaults is a set of object/array for this state slice.

Actions can also pass along metadata that has to do with the action. As we want to pass along how much hay and carrot a zebra needs.

@Action(FeedZebra)
  feedZebra(ctx: StateContext<ZooStateModel>, action: FeedZebra) {
    const state = ctx.getState();
    ctx.setState({
      ...state,
      zebraFood: [
        ...state.zebraFood,
        // this is the new ZebraFood instance that we add to the state
        action.zebraToFeed,
      ]
    });
  }

Select:

Selects are functions that slice a specific portion of state from the global state container. Slices of data from the store are selected by using the @Select decorator.

@Select(state => state.zoo.animals) animals$: Observable<string[]>;

The store class has a select function:

export class ZooComponent {
  animals$: Observable<string[]>;
 
  constructor(private store: Store) {
    this.animals$ = this.store.select(state => state.zoo.animals);
  }
}

NGXS vs NGRX

NGXS ang NGRX are both state management libraries for angular application. Both of them share redux principle. It depends on preferenece which one to choose as NGXS is more angularish because it uses modern typescript features.

Visit NGXS docs for further documentation.

Written by 

Rudar Daman Singla is the Trainee Software Consultant at Knoldus Software LLP. He has done B.Tech. from Jaypee University of Information technology, Waknaghat(Solan). He has good knowledge of languages C, C++, Java, Scala, HTML, CSS, PHP, Node and Angular. He is also interested in VFX. As a fresher, he always tries to explore the different type of software and tools.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading