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

What strategies can I use to streamline this array update function code?

Looking to simplify my updated array function. The update function involves updating and comparing values in an array. The comparison will be done within the fruit_temp. For example, data in fruit_temp's fruit_db_id corresponds to an existing id in th ...

Understanding the scope of jQuery variables within a function

myClass.prototype.toggle = function() { var elements = []; $.getJSON('http://localhost/jsoner.php', function(data) { $.each(data, function(index, value) { elements.push(value); alert(elements[0]); //this is functioning } ...

Having trouble getting the default NextJS template to work with TailwindCSS

Sysinfo: > Windows 11 > Node: v18.16.0 > Next: 13.4.13 > Tested Browser: Firefox, Chrome. Step to Reproduce To recreate the issue, I created a NextJS project using the command npx create-next-app tezz with specific options selected: Would you ...

Examples of using React tables with Material-UI, such as the Material-UI kitchen sink demo, will showcase how to

Can someone help me figure out why the values are not visible in the react table MUI kitchen sink? When I switch to JSON, the header is visible but the data in the table disappears. Both 'data' and 'data1' have the same structure accord ...

Exploring the internet with Internet Explorer is like navigating a jungle of if statements

I am facing an issue with my code that works well in Chrome, but encounters errors in IE. The if condition functions correctly in Chrome, however, in IE it seems like the first condition always gets executed despite the value of resData. Upon analysis thro ...

Guide to incorporating Bootstrap and its dependencies into a Chrome extension powered by Vue using npm

As I delve into the world of webpack, vue, and vuex to create a chrome extension, I encountered an issue with loading Bootstrap 4 within the extension. Despite using the correct path for the node modules folder, I keep getting a file not found error when t ...

Issue with form array patching causing value not to be set on material multiple select

When attempting to populate a mat-select with multiple options using an array of ids from Firestore, I encountered an issue. The approach involved looping through the array, creating a new form control for each id, and then adding it to the formArray using ...

Utilizing HighCharts' Reflow Feature for Dynamic Chart Resizing

Our Angular application utilizes highcarts-ng for implementing HighCharts. Check out the Chart Maximize and Minimize function that is currently operational: function expandChartPanel() { vm.chartMaxed = !vm.chartMaxed; viewHeader = ScopeFactory. ...

Deleting Firestore ancestor documents and sub-collections that do not exist

My goal is to tidy up my collection data. The collection I'm working with is named "teams". Within this collection, there is a sub-collection called "players". I used a basic delete query in Firestore to remove the document under ...

Unable to populate an array with JSON elements within a for loop triggered by useEffect

In my code, there is an issue with the array candleRealTimeDataQueue not updating correctly. Below is the snippet of the problematic code: let candleCurrentJSONDataWS = null; var candleRealTimeDataQueue = []; let tempDateTime = null; let ca ...

Implement a click event for the X-Axis label in Angular 2 Highcharts

I'm currently facing a challenge with hand-rolling a solution that involves adding a click listener to an X-Axis label in a column chart using the HighCharts API within an Angular 2+ application. Here is what I have gathered so far: I am utilizing ...

Methods to verify if an array contains a particular string within a PUG template

I'm currently working with NodeJS using Express and the PUG view engine. My goal is to determine whether an array includes a specific string. I've experimented with JavaScript's built-in methods like: array.includes(str) array.indexOf(str) ...

Update the content of the page without reloading images

Is there a way to refresh a webpage on click without refreshing the images, only the text content? Can this be achieved without clearing the cache? I attempted to refresh the entire page with the following JavaScript code: <script> $(".secon ...

Using Vue.js in conjunction with Gulp: A Beginner's Guide

Currently, I am working on a small project that involves gulp. I have a desire to incorporate vue.js into this project but do not have the knowledge on how to configure vue.js in the gulpfile.js. I am seeking guidance on the configuration of gulpfile to i ...

Is it possible to utilize the cv.imencode function in Opencv.js for exporting images in the webp format?

I'm looking to convert images from various extensions like png and jpg to webp format. I initially explored using OpenCV.js but was unable to locate the cv.imencode method for creating webp images. Can anyone confirm if this method is supported? If no ...

Load an external script once the page has finished loading by leveraging the power of $(document).ready() in conjunction with $.getScript()

Is it possible to load a script in the header of a website instead of at the bottom? I've been trying but it's not working as expected. Here is an example of what I'm attempting: HTML file: <!DOCTYPE html> <html lang="en"> < ...

What is the best method for implementing Datepicker translations in Angular?

I am looking to incorporate the DatePicker component in Angular, enabling users to select a date that can be translated based on their browser's settings. Any suggestions on how to achieve this? <mat-form-field appearance="fill"> ...

"Duplicate instances of the domain appear in the URLs of the images

After installing bagisto (a Laravel ecommerce app) on a fresh setup, I encountered an issue with the CMS where uploading a new logo to the channel would cause it to be added to the symlink. Despite everything appearing correctly in the public directory, th ...

Modifying an item within an array of Mongoose models

I am working with a model schema that looks like this: { _id: foo cart: { items: [ { id: number name: string, } ] } } My goal is to locate the document by its id and then modify the name value of the object in ...

"Mastering the art of passing variables within the index parameter for JavaScript push method

I need help passing a variable inside index in JavaScript push while working with Angular. Here is my current code: angular.forEach(Val, function (Value,Key) { angular.forEach(Value, function (Value1,Key1) { saveDetailArr.push({ 'option_i ...