'How to update $auth.user properties in Nuxt.js?

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?



Solution 1:[1]

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.

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2