I'm puzzled as to why my Vuex modules are not functioning properly. I keep receiving the error message: "[vuex]

I've been searching for hours and can't figure out why I keep getting this error message: [vuex] unknown mutation type: groceryStore/getStoreApple on all of the commits to the mutations in the groceryStore-module. I believe I'm following the correct steps, but clearly something is not right. Any assistance would be greatly appreciated in identifying what mistake I am making while trying to access my functions in the groceryStore-module.

Below is my index.js file located in src/store/index.js:

import Vue from "vue";
import Vuex from "vuex";
import * as groceryStore from "./modules/groceries";
Vue.use(Vuex);

export default new Vuex.Store({
  modules: {
   groceryStore: groceries,
  }
});

This is the module I'm attempting to access found in src/store/modules/groceries.js:

import { db } from "../../main";
const groceryStore = {
  namespace: true,
  state: {
    fruit: {},
    fish: {},
    meat: {},
    sauce: {},
    spices: {},
    vegetables: {},
    bakery: {},
    beverages: {},
  },
  // Mutations code here...
};

export default groceryStore;

And this is the component where I try to render the code located at src/views/Home.vue:

<template>
  <div class="home">
    <!-- Component rendering code ... -->
  </div>
</template>

<script>
// Script code ....
</script>

<style>
/* Styles go here... */
</style>

Lastly, here's the main.js file content:

import App from "./App.vue";
import router from "./router";
import store from "./store";
import Vue from "vue";

new Vue({
  router,
  store,
  render: (h) => h(App),
}).$mount("#app");

Answer №1

Following a brief exchange of comments, I delved into my resources and unearthed a relatively straightforward example of a Vuex Module that I had recently constructed. Here, I present the store, module, and component.

Your application is undeniably more intricate, but one notable distinction I observed in your Vuex store was how you imported your module:

import * as groceryStore from "./modules/groceries";

In contrast, I approached module importation in my store slightly differently:

import userModule from './modules/user-store-module.js'

Although I am not an expert on JavaScript modules, I thought it might be worth mentioning. Below are the source files I mentioned:

UPDATE: I included namespacing, getters, mutations, and additional functionality for components to utilize them.

/store/index.js

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

import userModule from './modules/user-store-module.js'

Vue.use(Vuex)

export default new Vuex.Store({
  modules: {
    userModule: userModule
  }
})

/store/modules/user-store-module.js

const userModule = {
  namespaced: true,
  state: () => ({
    users: [
      {
        id: 1,
        name: 'User1',
        gender: 'male'
      },
      {
        id: 2,
        name: 'User2',
        gender: 'female'
      },
      {
        id: 3,
        name: 'User3',
        gender: 'male'
      },
      {
        id: 4,
        name: 'User4',
        gender: 'female'
      },
    ]
  }),
  getters: {
    getMaleUsers: state => {
      return state.users.filter( user => user.gender === 'male')
    },
    getFemaleUsers: state => {
      return state.users.filter( user => user.gender === 'female')
    },
  },
  mutations: {
    addUser(state, newGender) {
      let nextId = state.users.length + 1;
      state.users.push({
        id: nextId,
        name: 'User' + nextId,
        gender: newGender
      })
    }
  }
}

export default userModule;

VuexModule.vue

<template>
  <div class="vuex-module">
    <div class="row">
      <div class="col-md-6">
        <h4>Users</h4>
        <table class="table table-bordered">
          <thead>
            <tr>
              <th>ID</th>
              <th>NAME</th>
              <th>GENDER</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="user in users" :key="user.id">
              <td>{{ user.id }}</td>
              <td>{{ user.name }}</td>
              <td>{{ user.gender }}</td>
            </tr>
          </tbody>
        </table>
        <button type="button" class="btn btn-secondary" @click="addUser">Add Random User</button>
      </div>

      <div class="col-md-6">
        <div class="row">
          <div class="col-md-12">
            <h4>Male Users</h4>
            <table class="table table-bordered">
              <thead>
                <tr>
                  <th>ID</th>
                  <th>NAME</th>
                  <th>GENDER</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="user in maleUsers" :key="user.id">
                  <td>{{ user.id }}</td>
                  <td>{{ user.name }}</td>
                  <td>{{ user.gender }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        <div class="row">
          <div class="col-md-12">
            <h4>Female Users</h4>
            <table class="table table-bordered">
              <thead>
                <tr>
                  <th>ID</th>
                  <th>NAME</th>
                  <th>GENDER</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="user in femaleUsers" :key="user.id">
                  <td>{{ user.id }}</td>
                  <td>{{ user.name }}</td>
                  <td>{{ user.gender }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        gender: 'male'
      }
    },
    computed: {
      users() {
        return this.$store.state.userModule.users;
      },
      maleUsers() {
        return this.$store.getters['userModule/getMaleUsers'];
      },
      femaleUsers() {
        return this.$store.getters['userModule/getFemaleUsers'];
      }
    },
    methods: {
      addUser() {
        let nextGender = this.gender === 'male' ? 'female' : 'male';
        this.gender = nextGender;
        this.$store.commit('userModule/addUser', this.gender);
      }
    }
  }
</script>

Answer №2

import * as supermarketItems from "./modules/supermarket";

This code snippet will provide you with an object containing all the exports from the specified file. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#import_an_entire_modules_contents)

In your specific scenario, it should return an object like:

{
     default: {} // your supermarket items object
}

Therefore, it is recommended to use the following syntax:

import supermarketItems from "./modules/supermarket";

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Add a click event to elements that match

I must admit that I am not particularly knowledgeable in Javascript/jQuery and my question might come across as trivial. However, I am trying to assign a click event to every element on the page with the following code: $(document).ready(function () { ...

Select items from object based on a specified array of IDs

I am facing a challenge with my list of objects that each have an array associated with them. For instance, take a look at this example: "-KpvPH2_SDssxZ573OvM" : { "date" : "2017-07-25T20:21:13.572Z", "description" : "Test", "id" : [ { ...

Issue with Three.js CanvasRenderer not displaying Mesh when using multiple materials

Encountering an issue with CanvasRenderer not rendering a Mesh that has multiple materials applied to a BoxBufferGeometry. The Mesh appears without any materials when using CanvasRenderer, but works as expected with WebGLRenderer. Check out the example co ...

Can anyone recommend a reliable continuous integration pipeline for StrongLoop and GitHub integration?

How can you effectively develop websites using strongloop and github/bitbucket, ensuring smooth transitions from development to testing to production? I understand the key components of a successful workflow, but I'm interested in hearing about strat ...

Ways to acquire ttf files from a third-party domain without encountering CORS issues

I am attempting to obtain a .ttf file from an external website for use in my web application. However, when I try the following code: @font-face { font-family: 'font'; src: url('http://xxx.xyz/resources/tipografias/font.ttf') forma ...

ReactJs - Reactstrap | Issue with Jumbotron displaying background color

I am trying to create a gray background using Jumbotron in reactstrap. After installation and reference in required places - index.js import 'bootstrap/dist/css/bootstrap.css'; Jumbotron has been implemented in SignIn.js - import Re ...

Using React refs to target multiple elements dynamically with the help of the map

My code effectively catches when the dropdown is clicked outside, and it's working well: displayOptions() { return _.map(this.props.selections, (option, index) => { return ( <div className="ui icon top dropdown" ...

ng-if directive does not show data in AngularJS

I have a dynamic collection of images and videos that I want to display one at a time. Specifically, when I click on an image ID, I want it to show the corresponding image, and when I click on a video ID, I want it to show the relevant video. Below is the ...

"Combining jQuery and JavaScript to handle form submissions in un

What happens when you combine the Javascript onSubmit handler and jQuery submit handler? <form action="" method="post" onSubmit="myJavascriptHandler();"> <input type="submit" /> </form> <script type="text/javascript"> $("form") ...

The error callback encountered {"readyState":4,"status":200,"statusText":"success"} while processing

When I make a call to this url, the response is a JSON object when done directly in the browser. However, when I try to do it via ajax using the following code snippet: $.ajax({ url: url, type: "GET", dataType:"jsonp", succ ...

How to prevent a directory from being copied in webpack within Vue CLI

Currently, I am working on a Vue3 project created using Vue CLI 5.0.1 In my setup, there is a public folder that contains static assets necessary for serving the application. However, this folder is quite heavy, around 1GB in size. Whenever I run the npm ...

Sending a JSON object as a map through AJAX to an MVC controller

I am looking to send a map (dictionary) to the MVC controller along with a string parameter. var reportName= 'ReportName'; var FilterValues = new Map([ [0, "value1"], [1, "value2"], [2, "value3"], ]); var model = { reportName: reportName, ...

What is the best method for retrieving the entire row data based on the maximum value in a column?

function findMaxValue() { var highestValue = Math.max.apply(Math, $('.sira').map(function() { return $(this).text() })) alert(highestValue); } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"& ...

Implementing VueJs and Bootstrap to assign a value to an <option> element: A step-by-step guide

What is the proper way to assign a value using v-for in an option element? I'm encountering an error with value="{{data.id}}" when I try to add the value. Here are the lists that I would like to include in the select options: [{"id":1,"name":"test1" ...

Resolving issues with CSS placement and resizing

I have been considering developing a UI toolkit that offers an intuitive and powerful way of setting the position and size of elements/widgets. Here are some examples of how it could be used (although they are not currently implemented): ui("Panel").size( ...

Modify the length of an array using a number input field

Currently, I am working with an array that contains objects and I want to dynamically change the number of objects in this array based on user input from a number type input box. Whenever the number in the input box is increased, I need to increase the len ...

How can I modify the color in vue-google-chart when a filter option is selected?

I created a stack column chart with a filter that changes the color to blue when selected. Here is my Vue app: https://codesandbox.io/s/vue-dashboard-chart-6lvx4?file=/src/components/Dashboard.vue I expected the selected color to match the color in the ...

EJS not displaying object values properly

I'm currently in the process of setting up a blog and I want to create a page that displays the titles of all the articles I've written. For example: List of Articles: * Title: Article 1 * Title: Article 2 * Title: Article 3 Below is my Schem ...

Guide to Implementing Vue.js in a Website With Multiple Pages

In my Laravel project, I am importing my app.js file in the following way: require('./bootstrap'); window.Vue = require('vue'); const app = new Vue({ el: '#app', data: {}, methods: {}, }); This app.js file is include ...

How can I ensure that Mongoose is case sensitive?

Currently, our authentication system is case sensitive for the email input. However, I would like to make it case insensitive. Here is the function in question: Auth.authenticate({ email, password }) Auth represents a mongoose Model that stores users in ...