Search code examples
ngxsngx-share

How to get previous state from NGXS store


In NGXS we have getState() to get the current state. Is there a way to get the previous state from the store? I am looking for a solution to this as I have to implement Undo/Redo kind of functionality. Thanks!


Solution

  • You can use the store.snapshot() method to get the snapshot of the store at that particular time. You can store the snapshot in a variable and then, in case of a re-roll, just use store.reset() with the snapshot.

    export class MyComponent {
    
      private initialSnapshot: MyStoreStateModel;
    
      constructor(private store: Store){
        this.initialSnapshot = store.snapshot();
      }
    
      // ... component logic / state modification logic
    
      rollback = () => this.store.reset(this.initialSnapshot); 
    }
    

    Adjust to your needs...

    Hope this helps a little :-)