ThatNorthernMonkey's avatar

Vuex anybody? "TypeError: this.$store.commit is not a function"

Yeah I'm trying to work my way through the Vuex documentation slowly, building up and refactoring as I go along. I'm a little stuck with setting some user state on the Vuex store from a components ready method so it can be accessed from other components. It's all pretty basic but I can't seem to get it to work hrrmm. Any help appreciated!

// app.js

require('./bootstrap');
require('vue-resource');

import Vue from 'vue';
import Vuex from 'vuex';
import App from './components/App.vue';
import store from './vuex/store';

const app = new Vue({
    store,
    el: 'body',

    components: { 
        App
    }
});
// store.js
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex)

const store = new Vuex.Store({

    state: {
        user: {}
    },

    getters: {
        getUser: state => {
            return state.user
        }
    },

    mutations: {
        setUser(state, user) {
            state.user = user
        }
    },

    actions: {
        setUser(context) {
            context.commit('setUser')
        }
// App.vue
<template>
    <div id="app">
    </div>
</template>

<script>
import { mapState } from 'vuex'

export default {
    computed: mapState({
        user: state => state.user
    }),

    ready() {
        this.$resource('/api/user/').get({}).then(function(response){

        // Ajax call working    
        console.log(response.data);

        // None of the below work: "TypeError: this.$store.commit is not a function"

        // this.store.commit('setUser', response.data)
        // this.store.dispatch('setUser', response.data)
        // this.$store.dispatch('setUser', response.data)
        this.$store.commit('setUser', response.data)
    })}
}
</script>
0 likes
4 replies
ThatNorthernMonkey's avatar
Level 1

After a bit of digging, I solved this by delcaring the state, getters etc. outside of the store instance and then injecting them in:

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

Vue.use(Vuex)

const state = {
    user: {},
    rankedSessions: []
}

const getters = {
    getUser: state => {
        return state.user
    }
}

const mutations = {
    setUser(state, user) {
        state.user = user
    }
}

const actions = {
    setUser(context, data) {
        context.commit('setUser', data)
    }
}

export default new Vuex.Store({
    state,
    getters,
    mutations,
    actions
})
1 like
kordy's avatar

Your solution solves my similar problem if I also added .default to the store import

const store = require('./vuex/store').default;
ToxicToast's avatar

Im getting an error here Error in created hook: "TypeError: Cannot read property 'commit' of undefined"

Somebody might help me?

Please or to participate in this conversation.