State Management in Angular Using NGXS - Part 1
Tags: programming, angular, security
Published: 2022-05-09 21:12:17

### See how it’s easy to manage your #Angular application’s state using #NGXS and learn how you can use NGXS with Auth0’s SDK to handle user-related functionalities.

### <br>

## Intro

State management is a key component when building applications. There are various approaches by which we can manage the state in an Angular application, each with its pros and cons.

This blog post will focus on using NGXS as our state management solution. We will look at how you can use NGXS to manage your application's state by building a Recipe Admin Dashboard application. We will also learn how to secure the application using Auth0 and how it works with NGXS.

## What Is NGXS

[**NGXS**](https://www.ngxs.io/) is a state management pattern and library for Angular. NGXS acts as a single source of truth for your application's state - providing simple rules for predictable state mutations.

NGXS is modeled after the CQRS pattern - a pattern implemented in state management libraries such as NgRx and Redux. NGXS combines this pattern with TypeScript's classes and decorators to create a state management library with minimal boilerplate.

## How Does NGXS Work

NGXS is made up of four main components - Store, Actions, State, and Select. These components create a unidirectional circular control flow from the component to the store (via Actions) and back to the component (via Selects). The diagram below shows how the control flows in NGXS.

![NGXS State Management Control Flow Diagram](https://images.ctfassets.net/23aumh6u8s0i/1MamGFzTw4qp4N0M1sU7rM/12823d598b1a171b1d0285cbc6650a4a/001_ngxs-how-it-works.png)

### Store

The **Store** in NGXS is a global state manager that dispatches actions to state containers and provides a way to select data slices out from the global state.

### Actions

**Actions** express unique events that happen in our application. Actions are how the application communicates with NGXS's Store to tell it what to do.

### State

**States** are classes that define a state container.

### Select

**Selects** in NGXS are functions that provide the ability to slice a specific portion of the state from the global state container.

## Prerequisites

Angular requires an [active LTS or maintenance LTS](https://nodejs.org/about/releases) version of Node.js. Angular applications also depend on [npm packages](https://docs.npmjs.com/getting-started/what-is-npm) for many features and functions. To download and install npm packages, you need an npm package manager such as [npm](https://docs.npmjs.com/cli/install) or [yarn](https://yarnpkg.com/).

This project has a server-side component that has to run in parallel when running the Frontend. Follow the instructions in the [Api Express Typescript Menu repo](https://github.com/auth0-cookbook/api_express_typescript_menu). You can read more about setting up the server-side with Auth0 in this [blog post](https://auth0.com/blog/node-js-and-typescript-tutorial-secure-an-express-api/).

This tutorial focuses on how to use Auth0 with NGXS. For more information on setting up Auth0 for Angular applications, follow the instructions on the [README](https://github.com/auth0-blog/spa_angular_typescript_dashboard/blob/main/README.md#register-a-client-application-with-auth0) or refer to this [blog post](https://auth0.com/blog/complete-guide-to-angular-user-authentication/#Connect-Angular-with-Auth0).

## Getting Started Quickly

I created a demo application with the basic structure and components to help you implement the NGXS-related part.

Clone the demo app and check out its starter branch:

```bash
git clone -b starter git@github.com:auth0-blog/spa_angular_typescript_dashboard.git
```

Once you clone the repo, make `spa_angular_typescript_dashboard` your current directory:

```bash
cd spa_angular_typescript_dashboard
```

Install the project's dependencies:

```bash
npm i
```

Run the project locally:

```bash
npm run start
```

> The starter project contains an admin dashboard with the ability to log in and log out using Auth0's SDK. The logged-in user can then view the dashboard and view, add, edit, and delete a menu item depending on the user's permissions.

## Devtools

You can use the [Redux devtools](https://github.com/zalmoxisus/redux-devtools-extension/) extension for Chrome or Firefox for debugging store-related operations.

To use this extension with NGXS, you'll need to add NGXS's devtools dependency to our project. You can do this using `npm`.

```bash
npm install @ngxs/devtools-plugin --save-dev
```

Import the `NgxsReduxDevtoolsPluginModule` in our `AppModule` and configure it based on your project's requirements. For this tutorial, you'll be using their default configuration. Open `app.module.ts` and add the following code 👇

```typescript
// src/app/app.module.ts

import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { HttpClientModule, HTTP_INTERCEPTORS } from "@angular/common/http";
import { AuthHttpInterceptor, AuthModule } from "@auth0/auth0-angular";

// ✨ New 👇
import { NgxsReduxDevtoolsPluginModule } from "@ngxs/devtools-plugin";

import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";
import { NavBarModule } from "./shared";
import { environment } from "src/environments/environment";

@NgModule({
  imports: [
    BrowserModule,
    HttpClientModule,
    AuthModule.forRoot({
      ...environment.auth,
      cacheLocation: "localstorage",
      httpInterceptor: {
        allowedList: [
          `${environment.serverUrl}/api/menu/items`,
          `${environment.serverUrl}/api/menu/items/*`,
        ],
      },
    }),
    AppRoutingModule,
    NavBarModule,

    // ✨ New 👇
    environment.production ? [] : NgxsReduxDevtoolsPluginModule.forRoot(),
  ],
  declarations: [AppComponent],
  bootstrap: [AppComponent],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthHttpInterceptor,
      multi: true,
    },
  ],
})
export class AppModule {}
```

### Running the app and turning on devtools

After following the steps in this section, you should see an option to activate Redux devtools in your toolbar when you run the app. Once activated, you should see a window with an interface similar to the image below.

![Redux devtools with NGXS](https://images.ctfassets.net/23aumh6u8s0i/5BldaqgcD8fMrBJSwwub07/1e05e1ea78231bcd90108de241d1ce69/002_ngxs-redux-devtools.png)


> You can learn more about these features from their [official documentation](https://github.com/zalmoxisus/redux-devtools-extension).

## Install NGXS

You can use `npm` or `yarn` to install NGXS's dependencies.

Using `npm`

```bash
npm install @ngxs/store --save
```

Using `yarn`

```bash
yarn add @ngxs/store
```

> At the time this post was written, the latest NGXS store version was `3.7.2`, which will be the version we will be using throughout the tutorial.

[Read more...](https://auth0.com/blog/state-management-in-angular-with-ngxs-part-1/?utm_source=content_synd&utm_medium=sc&utm_campaign=angular)