5

When I want to update $auth.user.balance:

methods:{
   test(){
      this.$auth.user.balance = 10;
   }
}

But it returns error:

Error: [vuex] do not mutate vuex store state outside mutation handlers.

How can I update these vuex properties in Nuxtjs?

Fred II
  • 581
  • 2
  • 11
  • 23

2 Answers2

15

Nuxt provides $auth.setUser() method to set user.

Use $auth.setUser() like so:

const userToUpdate = {...this.$auth.user}
userToUpdate.balance = 10;
this.$auth.setUser(userToUpdate)

Data updating in store always should be immutable.

So create a new reference of object before passing it to setUser to avoid the reactivity issue.

Radical Edward
  • 2,824
  • 1
  • 10
  • 23
  • In my case, when using this.$auth.user in a computed variable it was not updating the DOM, i've needed to use this.$auth.user directly. – Jonathan Arias Mar 02 '21 at 14:26
1

When you're using Vuex you should only mutate your state throught your mutations, in your Vuex you should create a mutation like this :

  setBalance(state, payload) {
    auth.user.balance = payload;
  },

and in your component you need to map your new mutation in your methods,

 ...mapMutations('auth', ['setBalance']),

don't forget to import the mapMutations from vuex

import { mapMutations } from 'vuex';

and in your component when you want to set a new value to balance you call

 test(){
         let newValue = 10;
         this.setBalance(newValue);
       }

You can learn more about mutations in Vuex store here in Vuex documentation