ailauli69
ailauli69

Reputation: 676

Vue.js how to call mutation in created or mounted hook?

In my vue.js app, I have a store.js file where I create and export a Vuex store, like so:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)


export const store = new Vuex.Store({
    state: {
        listCategories: [
          {id: 1, name: "hello"},
          {id: 2, name: "hello2"},
        ]
    },

    mutations: {

       pushCategories: (state, payload) => {
        state.listCategories.push(payload);
       },

In a vue component, I want to change the store.state.listCategories variable after an Ajax call like so:

import {mapActions} from 'vuex'
import {mapGetters} from 'vuex'

export default {

    data: function() {
      return {
         categories: this.$store.state.listCategories
      }
    },

    methods: {
        ...mapActions([
            'pushCategories'
        ]),

    },

    created() {
        var vm = this;

        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        $.ajax({
            url: '/ajaxRequest',
            type: 'POST',
            success: function(data) {
                vm.pushCategories({id:3,name:"new Category"});
            },
            error: function() {
                console.log("error");
            }
        }) 

    },

But it creates an error:

unknown action type: pushCategories

Any idea where this error comes from ?

Thanks a lot

Upvotes: 2

Views: 5328

Answers (1)

Felipe Guizar Diaz
Felipe Guizar Diaz

Reputation: 341

You're trying to map a mutator using mapActions, you should move your pushCategories method to the actions field for the store or use mapMutations in the component instead.

<div id="app">
  <ul>
      <li v-for="category in categories" :key="category.id"> {{ category.name }}</li>
  </ul>
</div>
Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
    listCategories: [
        {id: 1, name: "hello"},
      {id: 2, name: "hello2"},
    ]
  },
  mutations: {
    pushCategories: (state, payload) => {
      state.listCategories.push(payload);
    }
  }
})

const { mapMutations, mapState } = Vuex

const vm = new Vue({
    el: '#app',
  store,
  computed: {
    ...mapState({
        categories: 'listCategories'
      }),
 },
 methods: {
    ...mapMutations(['pushCategories'])
 },
 created: function () {
    this.pushCategories(
      {id: 3, name: "hello3"}
    )
 }
})

JSFiddle https://jsfiddle.net/pxz1uery/1/

Upvotes: 1

Related Questions