Search code examples
typescriptvue.jsvuexdefaultreset

reset state in VUEX after triggered function in mutations (VueJS)


I want to reset all values inside of my state to default when a method in mutations is triggered, which means all state values should not be filled anymore.

Normally I will fill my variables with some values from my vue components, but when reset_data is triggered i want to reset all to default.

How can I achieve this in VueX? Thank You!

STORE.TS:

export default createStore({
    state: {
        test1: "",
        test2: "",
        test3: "",
        test4: "",
        test5: "",
    },

    mutations: {
        reset_state(state) {
          //this function will be triggered from a component in my VueJS project
          //here I want to reset my state
        }
    }
})

INFO: I don't search for a solution to just declared every variable (test1, test2, ...) for it's own.


Solution

  • You can do something like this. Copy the object:

    let data = {
         test1: "",
         test2: "",
         test3: "",
         test4: "",
         test5: "",
    }
    
    export default createStore({
        state: { ...data },
    
        mutations: {
            reset_state(state) {
              state = { ...data }
            }
        }
    })
    

    You need to spread it to lose its reference.