1. 程式人生 > >State Management in Angular using Akita

State Management in Angular using Akita

In this article, we’ll explain the state management concept and how Akita helps us to facilitate the data flow in the application by managing it.

A state machine is any device that stores the status of something at a given time and can operate on input to change the status and/or cause an action or output to take place for any given change. — The State Machine

Simply put, it stores the state of any form of data and manages the state transition based on current state and action.

Why State Management is Important?

Web-apps are getting richer and more complex. Managing state is exponentially harder than it used to be.

Different parts of an application have different responsibilities, and those (components, directives, etc.) are segregated across many different files, but they all need to reflect the same underlying state.

A state management library gives you a convenient way to:

  • Model your application state
  • Derive computed values from it
  • Monitor it for changes

It gives us many benefits like handling normalized data (redundant models can be avoided), immutability and organized state transition, time travel ability, etc.

Introduction to Akita

Akita is a state management pattern, built on top of RxJS and based on object-oriented design principles.

Akita encourages simplicity. It saves you the hassle of creating boilerplate code and offers powerful tools with a moderate learning curve, suitable for both experienced and inexperienced developers alike.

Before we dive in, let’s examine Akita’s building blocks:

The Model

The general representation of the data model which the store is going to manage.

The Store

A Store is like a warehouse, where the data model is going to be stored. You can execute all the DML (Data Manipulation Language) with the help of Akita built-in store’s methods like add(), update(), delete() , setActive(), setError(), etc.

The Query

Simply database queries, which helps querying the store. The query results are available in two forms — reactive queries and synchronize queries.

You can run all the DDL (Data Definition Language) with the help of Akita built-in query’s methods like select(), selectAll(), selectEntity(), selectCount(), selectActive(), etc.

Two types of Stores

The Basic Store — when our model doesn’t represent a collection of entities, e.g., session, UI states, etc.

The Entity Store — when we need to maintain a collection of entities e.g., domain model, e.g., employee, student, etc.