Code Monkey home page Code Monkey logo

angular-reactive-state's Introduction


logo

Angular Reactive State

Reactive state management for Angular

Advantages

  • Provide a store for each Angular module
  • Flexible and customizable store services
  • Supports Redux Dev Tool Extensions

Getting started

Installation

NPM

npm i angular-reactive-state

Yarn

yarn add angular-reactive-state

Create a store

As we are following a decentralized store concept we create a separate store for each of our modules:

Run the following command to create a store service:

ng generate service <store-name>

Now we follow these steps to transform the generated into a reactive store:

  • the service class extends the Store class
  • the Store class wants the type information of how our state looks like
  • the super function adds a name for the store and the initial state

Example

// todo-store.service.ts
import { Injectable } from '@angular/core';
import { Store } from 'angular-reactive-state';

type TodoStoreState = {
  todos: string[];
};

@Injectable({
  providedIn: 'root',
})
export class TodoStoreService extends Store<TodoStoreState> {
  constructor() {
    super('TodoStore', {
      todos: [],
    });
  }
}

Subscribe the state

The UI components can inject the store service like this:

constructor(private todoStore: TodoStoreService) {}

To subscribe to the state of the todoStore there are different possbilities:

  • subscribe to the whole state at once
  • subscribe to a specific part of the state

Example

// subscribe to the whole state at once
this.todoStore.state$.subscribe(state => {
  console.log(state); // output: { todos: [] }
});

// subscribe to a specific part of the state
this.todoStore
  .select(state => state.todos)
  .subscribe(todos => {
    console.log(todos); // output: []
  });

The select method will only trigger an event if the value of the specific property of the state has been changed. In addition the returned values are deep copies of the values in the store, so it is can't cause any reference issues.

Usage with signals

Since Angular 17, Signals can be used instead of Observables. To achieve this, the function selectAsSignal can be used:

// get a signal of a specific part of the state
const myTodos = this.todoStore.selectAsSignal(state => state.todos);

Get state snapshot

Some operations only require the current state of the store and do not need to get notified about changes. These are cases where a snapshot of the latest state can be very helpful.

Example

// get a part of the state without subscribing to it
console.log(this.todoStore.snapshot.todos); // output: ['my todo']

Change the state

There are two possibilities to update the state in the store:

  • update a root-level property of the state
  • update the whole state at once

Example

// replace a root-level property of the state with a new value
this.todoStore.updateProperty('todos', ['my first todo'], 'add todo');

// update the whole state at once
this.todoStore.update(
  state => ({
    ...state,
    todos: [...state.todos, 'my first todo'],
  }),
  'add todo'
);

In combination with the snapshot functionality it would also be possible to update the state like this:

// manipulate the store by using latest values from snapshot
this.todoStore.updateProperty('todos', [
  ...this.todoStore.snapshot.todos,
  'new todo',
]);

Destroy Store

When a store service is not needed anymore it can be destroyed by calling the destroy method. This method ensures that no state changes are triggered to the subscribers of the store.

// store is not triggering events
this.todoStore.destroy();

Usage of Redux Devtools

To use the dev tools it is necessary to import the dev tools module:

import { StateDevToolsModule } from 'angular-reactive-state/dev-tools';

@Component({
  ...
  imports: [StateDevToolsModule],
  standalone: true,
})
export class AppComponent { ... }

or when there's a module

import { StateDevToolsModule } from 'angular-reactive-state/dev-tools';

@NgModule({
  imports: [StateDevToolsModule],
})
export class AppModule {}

angular-reactive-state's People

Contributors

pkief avatar

Stargazers

 avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.