Encountering the "TypeError: this.$state is not defined" error message while working with Vuex in a VueJS project

My objective is to authenticate the user with Firebase and manage the state using Vuex. Upon opening the app, I utilize the state to determine if the user is logged in and perform various actions accordingly. I am trying to retrieve a state to populate a variable within the data() method in the App.vue file; however, it seems that I am not referencing it correctly. When the page loads, the following error messages are displayed:

[Vue warn]: Error in data(): "TypeError: this.$state is undefined"
found in

---> <App> at src/App.vue
       <Root>

and

[Vue warn]: Property or method "isLoggedIn" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

found in

---> <App> at src/App.vue
       <Root>

App.vue

<template>
  <v-app>
    <router-view v-if="isLoggedIn"></router-view>
    <login v-else />
  </v-app>
</template>

<script>
import login from "@/views/Login";

export default {
  name: "App",
  components: {
    login
  },
  data() {
    return {
      isLoggedIn: this.$state.getters.user != null
    };
  }
};
</script>

<style>
</style>

store/index.js

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

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    user: null,
    status: null,
    error: null
  },
  mutations: {
    setUser(state, payload) {
      this.user = payload
    },

    removeUser(state) {
      this.user = null
    },

    setStatus(state, payload) {
      this.status = payload
    },

    setError(state, payload) {
      this.error = payload
    }
  },
  actions: {
    setUserAction({ commit }, payload) {
      commit('setUser', payload)
      commit('setStatus', 'success')
      commit('setError', null)
    }

  },
  modules: {
  },
  getters: {
    status(state) {
      return state.status
    },

    user(state) {
      return state.user
    },

    error(state) {
      return state.error
    }
  }
})

Answer №1

Ensure that you have the following code to properly initialize Vue and Vuex:

import Vue from 'vue'
import App from './App' // src/App.vue
import store from './store' // store/index.js

Vue.use(store)

new Vue({ store, render: h => h(App) }).$mount('#app') // Pay attention to the "store" attribute here

Now, within a component, you can access it using this.$store.state

As mentioned by @skirtle, utilize computed properties for reactive changes with Vuex

computed: {
  isLoggedIn () {
     return this.$store.getters.user != null // Remove .state
     // Alternatively, you can directly use the state as well
     // return this.$store.state.user != null
  }
}

In Vuex, make modifications to the state using mutations. It appears you already have a setUser mutation defined

setUser(state, payload) {
  state.user = payload // Make sure to update this.user to state.user
},

You can then update the state in the component using

this.$store.commit('setUser', this.user)

Additionally, you have created a setUserAction action that performs 3 commits. You can simply invoke it in a component with

this.$store.dispatch('setUserAction', this.user)

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

Canvas with a button placed on top

I am working with a canvas and trying to position an HTML element over it using CSS. My goal is for the button to remain in place on the canvas even when resizing the entire page. Here is the code I am currently using. https://jsfiddle.net/z4fhrhLc/ #but ...

Struggling to locate the element using xpath on a JavaScript enabled website in Selenium with Chrome

I have been attempting to extract data from a website that utilizes Javascript. Despite researching similar inquiries on xpath in Selenium, I have not found a solution. I initially tried using requests, but as the JavaScript doesn't load completely, I ...

Is it necessary to confirm the validity of url.format(urlObject)?

I have been exploring the NodeJS URL API and am particularly interested in the url.format(urlObject) method. My goal is to develop a function that first validates the urlObject before using the format function, and throws a TypeError if any of the key/valu ...

Resolving TypeError: matchesSelector method is not recognized within React component

I am currently integrating masonry-layout from the official website to create a masonry grid within my component. However, I encountered an issue where clicking on a rendered element triggers the error message TypeError: matchesSelector is not a function. ...

What is the best approach to managing a 204 status in Typescript in conjunction with the Fetch API

Struggling to handle a 204 status response in my post request using fetch and typescript. I've attempted to return a promise with a null value, but it's not working as expected. postRequest = async <T>(url: string, body: any): Promise ...

Center-align the text in mui's textfield

What I'm looking for is this: https://i.stack.imgur.com/ny3cy.png Here's what I ended up with: https://i.stack.imgur.com/vh7Lw.png I attempted to apply the style to my input props, but unfortunately, it didn't work. Any suggestions? Than ...

Navigating and retrieving information from JSON data

I'm working with JSON data that I have received: [{"pk": 7, "model": "pycourt_login.orders", "fields": {"status": 0, "delivered": false, "order_id": "6count1%2", "student_id": 5, "counterid": "counter1", "datetime": "2011-04-05 01:44:01", "dish": 6, ...

The extracted text from the window appears to be blank

When attempting to enclose a selected string between two characters, I am encountering an issue. For example, when selecting 'test' and clicking on the change button, the selected text should change to 'atestb'. However, although I am a ...

Tips for limiting the maximum number of characters in CkEditor 5 for react js

Is there a way to limit the amount of characters in a CKEditor textarea in a React JS environment? I'm trying to set a maximum character count for the text area in CKEditor Does anyone have any examples or suggestions on how to achieve this? retur ...

Bulk database upserts with promises

Currently, I am working on parsing a list of JavaScript objects and upserting them to the database one by one using Node.js. The process typically looks like this: return promise.map(list, return parseItem(item) .then(upsertSingleItemToDB) ...

The data from req.body is mysteriously missing from Postman

When sending the post request, I used raw and json format... Here is the header configuration This is the code: //app.js const port = process.env.PORT || 3000; const express = require ('express'); const app = express(); const jsonParser = re ...

Sending Several Forms to a File Using Ajax

Greetings! We are working on implementing multiple forms that will be submitted to a single page using ajax, and the data collected will then be inserted into a database: <form class="form-horizontal" onsubmit="return insertData()"> <div class= ...

Text words wrapped in a new line

Below is the code I've been utilizing to wrap lengthy text inputted by users in a textarea for leaving comments: function addNewlines(comments) { var result = ''; while ($.trim(comments).length > 0) { result += comments.substrin ...

"Implement a function in Node.js/JavaScript that creates a new JSON object if the ID matches with the ID of another

const data = [ { system: { id: "4gSSbjCFEorYXqrgDIP2FA", type: "Entry", content: { type: { name: "Author" } }, }, DataDetails: { shortSlugOption: { "en-us": "some value", "za-op": "random value" }, ...

Trouble with Angular toggle switch in replicated form groups

Currently, I have a form group that contains multiple form controls, including a toggle switch. This switch is responsible for toggling a boolean value in the model between true and false. Depending on this value, an *ngIf statement determines whether cert ...

Converting Custom Data Arrays to JSON using JavaScript

My goal was to create a utility function that can convert custom data (the type of data Sencha Touch stores use) into JSON format. I've made progress, but the function fails when dealing with complex data from the Twitter API, although it works fine w ...

The interactivity of data-ng-click in HTML is not functioning as expected

I need help with implementing the data-ng-click functionality for a dynamically created button. Can someone assist me with this? var table = document.getElementById("dashboard"); for( var i = 0; i < $scope.namesOfMembers.length; i++ ){ var row = t ...

I always attempt to utilize the const useStyles method within my class components

Currently, I am working on a project using the React Framework and the Material-UI library. I found my templates at https://material-ui.com/getting-started/templates/ --> Sign In I switched from a function component to a class component in order to u ...

Flashing Effect of Angular Ui-Bootstrap Collapse During Page Initialization

Below is the code snippet I've implemented to use the ui-bootstrap collapse directive in my Angular application. HTML: <div ng-controller="frequencyCtrl" style="margin-top:10px"> <button class="btn btn-default" ng-click="isCollapsed = ...

The stylesheet is linked, but no changes are taking effect

I've linked my template.php to style.css, and when I make changes in template.php, they show up fine. However, if I make changes in the stylesheet, nothing happens. What should I do? My website is not live; I'm working on it using a WAMP server. ...