1.0.2 ā€¢ Published 3 years ago

ngxs-history-plugin v1.0.2

Weekly downloads
-
License
-
Repository
github
Last release
3 years ago

ngxs-history-plugin

npm.io npm.io

This plugin is designed to work with the NGXS state management library.

With this plugin we are able to capture the state changes and revert (undo) to the previous state by dispatching an action

Demo

Demo

šŸš€ See it in action on Stackblitz

How to use

  1. Install from NPM
  2. Import the module in the app.module
  3. Use the undoable decorator
  4. Dispatch the undo action

1. Install from NPM registry

If you use npm

npm i ngxs-history-plugin

If you use yarn

yarn add ngxs-history-plugin

2. Import the module in the app.module

Import the package module

import { NgxsHistoryModule } from 'ngxs-history-plugin'

Import the Angular module

@NgModule({
  declarations: [AppComponent],
  imports: [
    NgxsModule.forRoot([], {
      developmentMode: !environment.production,
    }),
    NgxsHistoryModule.forRoot(), // <-- import the module
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}

You can optionally use the following PluginOptions

NameTypeRequiredDescription
historyLengthnumbernothe number of elements to keep in the history. Empty means no restriction

Example

@NgModule({
  declarations: [AppComponent],
  imports: [
    NgxsModule.forRoot([], {
      developmentMode: !environment.production,
    }),
    NgxsHistoryModule.forRoot({
      historyLength: 25, // <-- use the historyLength option
    }),
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}

3. Use the undoable decorator

Set the undoable decorator in the state file for the actions you want to handle.

Example:

@Action(AddTodo)
@Undoable(AddTodo) // <-- set the decorator and provide the action to handle
addTodo(ctx: StateContext<TodoStateModel>, action: AddTodo) {
  const state = ctx.getState()

  const newItem = {
    title: action.title,
  }

  ctx.setState({
    ...state,
    items: [...state.items, newItem],
  })
}

4. Dispatch the undo action

Import the Undo Action

import { NgxsHistoryUndo } from 'ngxs-history-plugin'

Dispatch the action

undo() {
  this.store.dispatch(new NgxsHistoryUndo());
}

Enjoy :)