The Vuex state keeps acting mysterious by claiming to be undefined

Here is my post.js located in src > store > post.js:

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

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        testState: 'Hello',
        TV: 0,
    },

    getters: {

    },

    mutations: {

    },

    actions: {

    }
})

This is my index.js:

import Vue from 'vue'
import Vuex from 'vuex'
import post from './post'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
  },
  mutations: {
  },
  actions: {
  },
  modules: {
    post
  }
})

Finally, I attempted to access the state in a component.vue:

<template>
  <div id="app">
    <h3>{{ testState }} {{ TV }}</h3>
  </div>
</template>

<script>
import store from './store'
import { mapActions, mapState, mapGetters } from 'vuex'

export default {
  name: 'App',
  data(){
    return {

    }
  },
  computed: {
    ...mapState(['testState'])
  }
}
</script>

However, an error keeps popping up on the console:

Property or method "testState" is not defined on the instance but referenced during render.

Upon inspecting the Vuex state in Chrome's devtools, I can clearly see that testState: 'hello' is present, verifying its existence.

Any advice or tips? Appreciate it!

Answer №1

If you're looking to enhance your Vuex setup, consider utilizing namespaced modules

// data.js
import axios from 'axios'

export default {
    namespaced: true,
    state: {
        message: 'Welcome',
        count: 0,
    },
    getters: {
     getMessage: state => state.message
    },
    mutations: {
      setMessage(state, payload) {
          state.message = payload
      }
    },
    actions: {
      updateMessage({ commit }, payload) {
         commit('setMessage', payload)
      }
    }

}
// index.js

import Vue from 'vue'
import Vuex from 'vuex'
import data from './data'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
  },
  mutations: {
  },
  actions: {
  },
  modules: {
    data
  }
})
// Component

computed: {
    ...mapState('data', ['message', 'count']),
    ...mapGetters('data', 'getMessage') // this.getMessage
},
methods: {
   ...mapActions('data', ['updateMessage']) // this.updateMessage('new message')
}

Answer №2

If you are utilizing a module, experiment with the following approach:

...mapState({userState:state=>state.data.user})

Ensure that your module does not create a store instance, it should resemble the following structure:

export default {
    namespaced: true,
    state: {
        user: 'John',
        age: 25,
    },

    getters: {
    
    },

    mutations: {

    },

    actions: {

    }
}

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

Can TypeScript and JavaScript be integrated into a single React application?

I recently developed an app using JS react, and now I have a TSX file that I want to incorporate into my project. How should I proceed? Can I import the TSX file and interact with it within a JSX file, or do I need to convert my entire app to TSX for eve ...

What is the correct approach to importing the Select class in JavaScript with WebDriver?

I'm having trouble using the Select function in my code to interact with a dropdown menu. I attempted to import Select from the "selenium-webdriver" package, but it doesn't seem to be working. All of the search results I've found on this top ...

Is the JavaScript Date object consistently displayed in the America/New_York timezone?

The server sends me a time-stamp in milliseconds (Unix time / time from Epoch) with the constant timezone "America/New_York". On my client side, I want to ensure that the time is displayed according to the America/New_York timezone. I have been using Joda- ...

Solution: "The Mongoose Model.find method consistently provides an empty result set."

Currently, I am utilizing mongoose in combination with next.js to interact with an existing collection. Despite the collection not being empty, the mongoose model.find() function consistently returns an empty array. Below is my model code: const mongoose ...

Ways to determine if new data has been added to a MySQL table

Can anyone explain how the Facebook notification system operates? Here is my code snippet: (function retrieve_req() { $.ajax({ url: 'request_viewer_and_its_utilities.php', success: function(data) { $('.inte ...

Utilizing an Ajax call within "for" loops can result in skipping either odd or even iterations

Seeking assistance because we are facing a challenge that we cannot seem to overcome. Despite researching on platforms like StackOverflow and search engines, implementing a solution or solving the problem remains elusive. The goal is to develop a JavaScri ...

What is the best method for aggregating multiple JSON responses into a single array?

I am struggling to get my data in the desired format of [{..},{..},{..}]. I have created an empty array using const arr = [], but when I push all JSON data into this array, the output shows as separate arrays. How can I fix this issue? // const arr = [] co ...

Oops! You're trying to perform actions that must be plain objects. If you need to handle async actions

I have been struggling to implement Redux and pass an object into the store. Although I am able to fetch the correct object when I call the action, the store remains unchanged when I use store.dispatch(). It still only reflects the initial state. I've ...

What do you do when schema.parseAsync cannot be found?

Currently facing an issue with zod validation in my Node.js environment, specifically encountering the error: TypeError: schema.parseAsync is not a function Despite attempting various solutions like re-importing and troubleshooting, I am unable to resol ...

Leverage the power of JavaScript functions within the app.component.ts file of

I have a JavaScript file named action.js and I am trying to incorporate it into an Angular project. After doing some research, I found out that the js file should be placed in the assets folder and the path must be referenced in the scripts array within an ...

Utilizing the 'container' property in a React.js React-Bootstrap modal

How can I open a modal within a designated container using the native property "container"? Whenever I specify the class name of the container element, I encounter an error TypeError: Cannot use 'in' operator to search for 'current' in ...

When attempting to import and utilize global state in a component, the error message "Cannot iterate over null object"

I am in the process of setting up a global state to keep track of various properties that I need to pass down to multiple components. const initialState = { username: '', selectedCategory: null, categoriesList: [], createdTaskTopi ...

display and conceal a division by clicking a hyperlink

How can I make a hidden div become visible when clicking on a specific link without using jQuery? Javascript function show() { var a = document.getElementsByTagName("a"); if (a.id == "link1") { document.getElementByID("content1").style.v ...

Assign a value to a locally scoped variable within an iteration in Angular 2

Within my Angular code, I have the following HTML snippet: <span *ngIf="ControllerType?.AttributeID =='Controller Type'"> <select multiple name="ControllerType.Default" [(ngModel)]="Contro ...

Encountering the error "TypeError: Unable to access property 'findAll' of undefined" when using Sequlize

Currently, I am in the process of developing a CRUD Application utilizing PostgreSQL, Sequelize, and Express. I have been referring to this specific tutorial as my guide. However, it appears that there might be an issue with either my model or database con ...

What is the best way to pass default event argument alongside another argument in React?

This snippet demonstrates the function I wish to call when a certain input type is invoked: _handleOnEnterPress = (e, receiverUserId) => { if (e.keyCode === 13) { // assuming keycode 13 corresponds to 'enter' console.log("pressed ...

When positioned at high or low angles, the camera starts acting strangely

In my Three.js scene, I have a camera that I need to move and change its angle around a specific focal point. The focal point is actually the camera's position, and during rendering, I translate the camera by using the cameraBuff vector to position it ...

The query parameter is not defined in the router of my Next.js app API

I'm currently working on building an API endpoint for making DELETE requests to remove albums from a user's document in the MongoDB Atlas database. Struggling with an error that keeps popping up, indicating that the albumName property is undefin ...

Checking a bcrypt-encrypted password in an Express application

I am encountering an issue with my login password verification code. Even when the correct password is entered, it is not being validated properly. Can anyone provide assistance with this problem? login(req, res) { const { email, pass } = req.body; ...

Creating a blank grid using ng-repeat in angularJS

I'm attempting to create an empty grid using angularJS, but I've only been working with it for 2 days so I'm not very experienced. This is what I have come up with so far: <!doctype html> <html ng-app> <head> < ...