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!
4 Answers
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 :-)

- 2,677
- 17
- 27
@Mark Whitfield is correct that there is no direct way to get the previous state with NGXS. Using NGXS I had a use case where I wanted to know the previous value to perform an undo-style operation.
I used the regular NGXS @Selector
syntax to tap into the state slice I was interested in, then in I subscribed directly to that Observable
and used the rxjs pairwise operator to give me the new emitted value and the previous value. Worked well for the way I wanted to consume those values so it might fit what you are after.

- 7,611
- 3
- 30
- 39
There is no way to get the previous state by default, but you can definitely create a service that monitors the state and pushes a copy into its own stack.
You can then restore this state using the reset
method on the store.
You would probably use the select
and reset
methods of the store
. See here for more info: https://ngxs.gitbook.io/ngxs/concepts/store#selecting-state

- 6,500
- 4
- 36
- 32
You can use "redux-undo" from npm to implement undo and redo. It is pretty simple and straight forward. You can find the docs here

- 81
- 4