What are the steps for building modules using Vuex and fetching data using mapState()?

I've been experimenting with separating my Vuex code into modules, but I'm having trouble retrieving data using mapState().

What's the most effective approach for creating modules and utilizing mapping?

Here's the structure of my store folder:

├── store
│   └── index.js
|   └── testStore.js
|

In my index.js, the setup looks like this:

import Vue from "vue";
import Vuex from "vuex";

import { testStore } from './testStore'

Vue.use(Vuex);

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

In the testStore.js file, I define the following:

export const testStore  = 
{
    namespaced: true,
    state,
    mutations,
}

const state = 
{
    social: false,
  normal: true,

};
const mutations = 
{
    // setters
    setSocial(state, payload) {
      state.social = payload;
    },
    setNormal(state, payload) {
        state.normal = payload;
    },
};

To test it out, I created a simple component (using Vuetify):

The testComponent.vue file contains:

<template>
  <v-container>
    <v-layout justify-center>
        <v-btn class="primary" @click="displaydata">test</v-btn>
    </v-layout>
  </v-container>
</template>

<script>

import { mapState, mapMutations } from 'vuex'

export default {
    computed: {
        ...mapState('testStore',['normal','social']),
    },
    methods: {
        ...mapMutations('testStore',['setNormal','setSocial']),

        displaydata() {
            // eslint-disable-next-line
            console.log(this.normal);
            // eslint-disable-next-line
            console.log(this.social);
        } 
    }
};
</script>

However, when I click on the "test" button, the console shows: undefined.

Can anyone help me figure out what's going wrong with this setup? :(

Answer №1

Here is a straightforward solution that I overlooked:

In the file testStore.js, the placement of export const testStore was incorrect.

The correct version of testStore.js should have the export statement at the end instead:


const state = 
{
    social: false,
    normal: true,

};
const mutations = 
{
    // setters
    setSocial(state, payload) {
      state.social = payload;
    },
    setNormal(state, payload) {
        state.normal = payload;
    },
};

export const testStore  = 
{
    namespaced: true,
    state,
    mutations,
}

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

Encountering a Problem When Exporting a Class Using Require

I find myself struggling with a particular detail that eludes me. Despite exploring numerous suggested solutions found through Google, I am overwhelmed by the uncertainty of what actually works. Here is MyProject on Replit and the problematic class I&apos ...

I'm encountering an error when trying to return a value using the question mark operator in Vue.js - can someone explain why

When I attempted to retrieve the value using the question mark operator instead of using return twice, I encountered an error stating "Cannot read property 'omitDescription' of undefined." buttonText() { return this.omitDescription ? 'プ ...

Warning is not triggering upon redirection from another page

I'm encountering an issue with the following code within the body tag of a view in MVC. The alert message displays the first time the page loads, but it doesn't execute when the control is coming through a redirect. Despite setting breakpoints a ...

Notify App.vue that a Service Worker event is being triggered

In my project built with Vue CLI 3 and the Vue PWA plugin, I want to implement a banner that prompts users to click an in-app “Refresh” link following the instructions provided here in the 'Approach #3' section. The challenge lies in integra ...

Challenges encountered when passing objects with Angular 2 promises

I am encountering a problem when using a promise to retrieve a Degree object in Angular 2. The initial return statement (not commented out) in degree.service functions correctly when paired with the uncommented implementation of getDegree() in build.compon ...

Issue: The initial parameter should be a File or Blob object

Hey there! I'm currently utilizing the compressorjs plugin for compressing images, but I'm encountering an issue when selecting images. You can find out more about the plugin here. Here is my code snippet: window.resolveLocalFileSystemURL( ...

Is it possible for the scroll event to be triggered while scrolling only when a div element is used?

While utilizing window.onscroll to track scroll events during scrolling, I noticed that in certain Android devices the scroll event is only triggered after the scroll has completed. However, when monitoring scroll events within a specific div element, it ...

Adjust the button's hue upon clicking it

The current function is operational. Upon pressing the button, it toggles between displaying "click me" and "click me again". However, I desire the button to appear blue when showing "click me" and red when displaying "click me again". <!DOCTYPE html ...

Express.js Passport.js throws an error when req.user is not defined

The middleware function below is unable to access req.user or determine if the user is logged in after they log in. I have confirmed that passport.serializeUser is successful after logging in and that req is defined when accessed from the middleware funct ...

Increase the Speed of setInterval in JavaScript

I'm currently experimenting with gradually decreasing the interval at which a function is executed within a setInterval method. Below is a simplified example code snippet: var speed = 100; window.setInterval( speed -= 0.01 , speed); I suspect that ...

Assigning index values to child rows in AngularJS: a step by step guide

One of my requirements involves assigning index values to child rows. The structure includes group rows with child rows underneath. Currently, I am using ng-repeat along with $index for the children as shown below: HTML code: <table ng-repeat="nod ...

Set up a single array containing multiple objects in a table, each with its own unique set of keys

I am currently developing an application that retrieves data from one or multiple databases, each with different names and varying numbers of columns. The goal is to consolidate this data into a single report screen and export it as a table. While the tabl ...

Incrementing a variable based on a condition in JavaScript

Currently, I am working on a project where I have a variable called "total" that needs to be assigned a number (or price) and then incremented when certain options are selected or checked. Below is the code that I have developed up to this point. This sni ...

Troubles emerge when incorporating the AOS library into main.js in Vue 3

Hey there! I'm currently incorporating the Aos library into my Vue 3 project and encountering issues. import App from './App.vue' import AOS from 'aos' import 'aos/dist/aos.css' import { createApp } from "vue" ...

The v-model in the Vue data() object input is not functioning properly and requires a page refresh to work correctly

Explaining this situation is quite challenging, so I created a video to demonstrate what's happening: https://www.youtube.com/watch?v=md0FWeRhVkE To break it down: A new account can be created by a user. Upon creation, the user is automatically log ...

"Create a New Browser Tab When User Interacts with a Hyperlink leading to an External Website

I am currently working on a recommendations app built with React and I want to enable users to navigate to external websites when they click on a component that displays information about that website. At the moment, I have implemented a wrapper that, upo ...

"Troubleshooting issue: Module fails to reload following JSON.parse error

For QA testing purposes, we have a test page that allows our QA team to replicate server behavior by passing JSON to a mock service. Everything functions correctly when valid JSON is used, but if invalid JSON is provided, an error is returned - which is ex ...

How can I implement pagination using jQuery?

I'm looking to incorporate jQuery pagination in my CodeIgniter project. After doing some research on the CodeIgniter forum and CodeIgniter AJAX Pagination Example/Guideline, I came across suggestions to check out a solution on TOHIN's blog. Howe ...

Troubleshooting Django Python: Why can't I retrieve a JS object sent via AJAX in my Python QueryDict?

As I work on my Django project, I've set up a system for data exchange between the server and client using javascript and python with AJAX. To make things easier, I created a config object in JS to store important parameters that both the server and J ...

Vue - understanding the process of validating information from Vuex store

My project involves a complex form with approximately 17-20 fields, potentially influenced by the status of a checkbox. The intention is to submit this form to an API backend. The proposed strategy includes validating the user input using Vuelidate and pr ...