Reset Vuex state to initial values

I have all my initial Vuex state values in a separate file. So as a mutation:

import initialState from './initialState'

This obviously doesn’t work:

resetState(state) {
    state = Object.assign({}, initialState);

But if I try and use for…in loops and copy value-by-value, that doesn’t work either.

This shouldn’t be so hard. At the moment my easiest solution seems to be to just call location.reload() which is mental! Help?

OK, figured it out. In mutations:
state.js exports one function that sets all the initial values.

import Vue from 'vue';
import initialState from './state.js';

export default {

resetState(state) {
    let reset = initialState();
    for (let f in state) {
        Vue.set(state, f, reset[f]);
1 Like

I found this approach worked nicely:

resetState(state) {
    Object.assign(state, initialState);

You could take it easy by tiny package: vuex-extensions

Check out the example on CodeSandbox

Creating Vuex.Store

import Vuex from 'vuex'
import { createStore } from 'vuex-extensions'

export default createStore(Vuex.Store, {
  plugins: []
  modules: {}

Store resets to initial State

// Vue Component

// Vuex action
modules: {
  sub: {
    actions: {
      logout() {