0

I'm trying to update a state and i get this error: Error: [vuex] do not mutate vuex store state outside mutation handlers.. The following creates state for categories.

register.vue , i can see the state categories in vuex is updated.

async saveCategories(){
    if(this.selectedCategories.length) {
        this.$store.dispatch('app/Categories', this.selectedCategories);
        this.$router.push(`/dashboard`);
    }
  }

dashboard.vue, when i try to update the state with new selectedCategories in method updateCategories, the state categories isn't updated when i check vuex in chrome extension

async mounted() {    
    if(this.$store.state.app.Categories.length) {
    this.selectedCategories = this.$store.state.app.Categories.map((category: any) => {
        return parseInt(category);
    });
    }
        
  }

   updateCategories() {    
     this.$store.dispatch('app/Categories', this.selectedCategories);
   }

I get this error Error: [vuex] do not mutate vuex store state outside mutation handlers.

this is how i access the state this.$store.state.app.Categories

How do i solve?

user892134
  • 3,078
  • 16
  • 62
  • 128

1 Answers1

0

This happens because you can do an action in store instead of in a component. this.$store.state.app.Categories.map((category: any) => parseInt(category));
The solution is to create a mutation for this and instead call that mutation in the component.

state: {
  app: {
    Categories: []
  }
}

mutations: {
  toInt(state) {
    state.app.Categories.map((category: any) => parseInt(category))
  }
}

Register.vue

async mounted() {
  this.$store.commit('toInt')
}
kissu
  • 40,416
  • 14
  • 65
  • 133
Amini
  • 1,620
  • 1
  • 8
  • 26
  • Hi, please do not make it `async mounted`if calling a **sync** mutation. Otherwise, please recommend a Vuex action. – kissu Nov 02 '22 at 12:21