How to time travel(rollback) in a state tree using Vuex?

8k views Asked by At

How can I achieve a time travel feature using Vuex ? I want to go back for a previous state, to undo something.

Is that possible out of the box ?

Any idea on how to achieve that ?

was hoping for something like store.rollback(1)

2

There are 2 answers

1
CodinCat On

Just implement it by your own, add a prevState to your store, you can only select the parts that you want to make it undo-able.

Here is the simplest example, which only support 1 history record:

store

const state = {
  count: 0,
  prevCount: null
}

mutations:

const INCREMENT = state => {
  state.prevCount = state.count
  state.count += 1
}

const UNDO = state => {
  if (state.prevCount !== null) {
    state.count = state.prevCount
    state.prevCount = null
  }
}

If you need to have more history, just put them in an array

const state = {
  count: 0,
  countHistory: []
}

and then you can use state.countHistory.pop() and state.countHistory.push(xx) to undo/save records

Another solution is plugin (middleware), in case you want to save all the history automatically.

0
Jan Franciszek Cieślak On

The best approach is not to keep the record of the state snapshots, but rather, keep the record of committed mutations.

To UNDO one step:

  • reset the state to initial
  • reapply all mutations but last

This approach is easier on the memory (esp if you have a large store), and is more in line with how the store should be treated.

A very good breakdown here:

https://vuejsdevelopers.com/2017/11/13/vue-js-vuex-undo-redo/

A working solution here:

https://github.com/anthonygore/vuex-undo-redo