w11k / Tydux

Type safe state management for web applications
Apache License 2.0
36 stars 4 forks source link
cqrs flux-architecture redux rxjs statemanagement typescript

Build Status npm version

Tydux Logo

Encapsulating State Management Library

Tydux is a state management library implemented in TypeScript with a strong focus on encapsulation, type safety and immutability. It can be used standalone or hook into existing Redux-based (or compatible) application.

The key concepts are:

If you know Redux:

Tydux shares the concept of state, actions, reducer and selectors but differs in the way they are implemented:

Key benefits:

Installation

Install Tydux and all required peer-dependencies:

npm install @w11k/tydux rxjs redux @redux-devtools/extension immer.

Quick Overview Demo

Well will need at least a state, the commands and the facade.

Create the state class:

You can implement the state with a class or a plain JavaScript object. Classes are a bit more convenient but remember that you must not use inheritance and that the class only contains fields.

export class TodoState {
  todos: ToDo[] = [
    {isDone: false, name: 'learn TypeScript'},
    {isDone: true, name: 'buy milk'},
    {isDone: true, name: 'clean house'},
  ]
}

Create the commands:

Commands are grouped within a class and can alter the state via this.state. You can manipulate nested properties of the state.

export class TodoCommands extends Commands<TodoState> {

    clear() {
        this.state.todos = [];
    }

    setTodoList(todos: ToDo[]) {
        this.state.todos = todos;
    }

    toggleTodo(name: string) {
        const todo = this.state.todos.find(it => it.name === name)
        todo!.isDone = !todo.isDone
    }

}

Note that the state object can be directly modified deeply and does not need to be copied. To achieve this, the library immer is used. The state may consist of plain Javascript objects, maps, sets and arrays. Additionally, we add the immerable symbol for you, if using classes.

Create the facade:

After we created the state and commands, we combine them within a facade.

export class TodoFacade extends Facade<TodoCommands> {

  constructor() {
    super(
        'todos',                // the 'mount point' within the global state 
        new TodoCommands(),     // commands instance defined above
        new TodoState()         // initial state
    );
  }

  /**
   * in our facade we can do synchronous or asynchronous stuff (action or effect)
   */
  async loadTodoListFromServer() {
    this.commands.clear();
    const list = await fetch("/todos");
    this.commands.setTodoList(list);
  }

  /**
   * simple delegate to a command method
   */
  toggleDoneStateOf(t: ToDo) {
    this.commands.toggleToDo(t.name);
  }

}

Bootstrap:

After we created the state, commands and facade, we can bootstrap Tydux.

  1. Create a TyduxStore and provide the global initial state (optional, defaults to {}). Every facade's state is part of this global state.
  2. Register the TyduxStore as global store.
  3. Instantiate the facade(s).
// Create and register the tydux store
const tyduxStore = createTyduxStore();      // 1.
setGlobalStore(tyduxStore);                 // 2.

// instantiate every facade once
const todoFacade = new TodoFacade();        // 3.  

Usage:

// get the current state
const todos: ToDo[] = todoFacade.state.todos;

// subscribe to state changes
todoFacade.subscribe(state => {
    const todos: ToDo[] = state.todos;
});

// call facade methods
todoFacade.loadTodoListFromServer();

Documentation

Patron

❤️ W11K - The Web Engineers

❤️ theCodeCampus - Trainings for Angular and TypeScript