Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vue.js

vuex

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)

like image 245
Cassio Cabral Avatar asked Dec 27 '16 18:12

Cassio Cabral


2 Answers

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

like image 161
Jan Franciszek Cieślak Avatar answered Sep 22 '22 14:09

Jan Franciszek Cieślak


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.

like image 24
CodinCat Avatar answered Sep 20 '22 14:09

CodinCat