Search code examples
vue.jsvuex

Vuex: how to tell if a state is dirty/pristine after some user input?


I have a bunch of user-editable Vuex modules. The changes are only being persisted when the user actually hits save, however, I'd like to handle cases when there are unsaved changes.

My current approach is adding an isEdited boolean flag, that way I can both show a notification and prevent navigating away with a confirm dialog.

However, if a user makes a change and then undoes it, I have no way of telling that the current state is just the same as the one that was initially loaded.

Of course I could duplicate the state and compare it against the current state, but that feels like way too much overhead for such a simple feature.

Can anyone recommend a better approach?


Solution

  • Vee-validate can provide you such thing (focused on user inputs):

    You can check if there it's dirty or not there.

    PS: there are maybe other packages doing things like Vee-validate but that one is a nice one!


    You can also of course use a comparison with a cloned object alongside, but that may be quite heavy if this is a big one with a lot of nested fields (be careful as of how to properly compare 2 objects in JS too, lodash is probably recommended).


    You could use useRefHistory to create a history and add/remove from the stack.
    Different approach but still a totally viable/good one IMO.


    You could ignore the whole thing.
    If you don't want too much overhead, this is still the best way to go.
    Also, that will not happen every time. And when it does, it will not be a huge deal anyway (IMO).