Vue3 vuex "TypeError: vuex__WEBPACK_IMPORTED_MODULE_1__.Store.commit is not a function"

Viewed 1022

So, i'm trying to get static json data through axios and commit it to the "projects" state in vuex, but I'm getting the error "Store.commit is not a function".

Am I missing something?

Do keep in mind that I am doing this in Vue3's vuex.

//store.js
import axios from 'axios';
import { createStore, Store } from 'vuex'


export default createStore({
  state: {
    projects:[]
  },
  mutations: {
    SET_PROJECTS: (state, projects) => {
      state.projects = projects;
    }
  },
  actions: {
  },
  modules: {
  }
});

const getPrjectData = () => {

  axios
  .get('static json URL here')
  .then(response => {
    Store.commit('SET_PROJECTS', response.data.projects);
  })
  .catch(err => console.log(err));   
}

getPrjectData();

1 Answers

Convert the function to an action:

actions: {
  getPrjectData({ commit }) {
    axios
    .get('static json URL here')
    .then(response => {
      commit('SET_PROJECTS', response.data.projects);
    })
    .catch(err => console.log(err));   
  }
}

Call the action like:

Options API

this.$store.dispatch('getPrjectData');

Composition API

import { useStore } from 'vuex'
export default {
  setup() {
    const store = useStore();
    store.dispatch('getPrjectData');
  }
}
Related