Unlocking the secret to accessing state in a JavaScript file using VUEX

Can anyone help me figure out why I can't access the currentUser property from the state in my vuex store's user.js file? I'm trying to use it in auth.js, but when I write: store.state.currentUser.uid === ...

This is the error message I'm getting:

Cannot read property 'state' of undefined.

What am I missing in the code?

Here is the directory structure:

src
 store
   user
    |>user.js
    |>mutations.js
   index.js
 auth.js

user.js:

 const state = {
   profile: {},
   loggedIn: false,
   currentUser: null,
   userProfile: {}
 }

 export default {
   namespaced: true,
   state
 }

auth.js:

import store from './store'
const fb = require('./firebaseConfig.js')

fb.auth.onAuthStateChanged(user => {
 if (user) {
  fb.postsCollection.orderBy('createdOn', 'desc').onSnapshot(querySnapshot => {

  let createdByCurrentUser
  if (querySnapshot.docs.length) {
    createdByCurrentUser = store.state.currentUser.uid === 
      querySnapshot.docChanges()[0].doc.data().userId ? 'Yes' : 'No'
    console.log(createdByCurrentUser)
   }
 })
 }
})

index.js

import Vue from 'vue'
import Vuex from 'vuex'
import user from '@/store/user'

Vue.use(Vuex)

const store = new Vuex.Store({
 state: {
   awesome: true
 },
 modules: {
  user
 }
})

export default store

https://i.sstatic.net/gdSep.png

Answer №1

For accessing the current user, make sure to utilize the getters. Refer to the documentation for more details: here

Below is an example of using getters:

export default {
  currentUser
}

function currentUser({ currentUser }) {
  return currentUser;
}

Implementing this in your project:

import getters from './getters'

export default {
  namespaced: true,
  state: {
    profile: {},
    loggedIn: false,
    currentUser: null,
    userProfile: {}
  },
  getters
}

To access the current user in your application:

import store from './store';

const currentUser = store.getters['user/currentUser'];

Remember, due to the module being namespaced, you must use its name as a prefix to retrieve the getter function.

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

Does CSS in the current IE9 beta allow for text shadows to be implemented?

Text shadows look great in Firefox and Chrome. For example, I have a basic website for streaming videos. Unfortunately, there are no shadows in IE9 for me. This is my CSS code: p { color: #000; text-shadow: 0px 1px 1px #fff; padding-bottom: 1em; } ...

Generating various arrays of data

I am currently facing an issue with creating separate datasets based on the month value. Despite my efforts, all month values are being combined into a single dataset in my code. Any assistance in dynamically generating different datasets would be greatly ...

When utilizing Route.get() with an express app, an error occurred as a callback function was expected, but instead, an [

My health.js file contains the following code: var health = function(req, res, done) {}; health.prototype.endpoint = function(req, res, done) { let http_status = 200; console.log("--- Sending health endpoint status of %s", http_status); res.se ...

Is there a way to render a component without having to render AppComponent constantly?

I am looking to display two components (AppComponent and UserComponent) without constantly displaying AppComponent. Here's how my code is structured: app.routing.module.ts const routes: Routes = [ { path: '', component: AppComponent ...

Is it possible to store dat.gui presets for controls that are dynamically added?

I have a dynamic dat.gui interface where I add controls, but the "save settings" feature doesn't seem to recognize them. var mygui = new dat.GUI(); mygui.remember(mygui); // Example of adding a control in the standard way mygui.control1 = 0.0; var c ...

What is the process for adding new data to a data source without overwriting existing information?

I need assistance with a react native app I am developing. I am currently facing an issue where the data received from a fetch request needs to be displayed in a list view. However, each time new data is fetched, it overwrites the previously received data ...

My element is not being animated by Elementbyclass

Without Using JQUERY The animation I'm trying to create isn't functioning properly. I attempted to utilize document.getElementsByClassName, but it's not working as expected. There are no errors, but the element is not animating correctly. ...

What are some effective strategies for bypassing CORS requirements in Vue client-side and server-side applications?

I found this amazing MEVN stack tutorial that I've been following: MEVN Stack Tutorial The tutorial is about creating a blog post app, where the client side is built using Vue (referred to as app A) and the backend is built on Express.js providing d ...

Printing the elements of an array in a repetitive sequence

var arr = [a, b, c]; In this specific array setup, index 0 corresponds to "a", index 1 corresponds to "b", index 2 corresponds to "c". console.log(arr[0]) // will output > "a" console.log(arr[1]) // will output > "b" console.log(arr[2]) // will ...

Grouping elements of an array of objects in JavaScript

I've been struggling to categorize elements with similar values in the array for quite some time, but I seem to be stuck Array: list = [ {id: "0", created_at: "foo1", value: "35"}, {id: "1", created_at: "foo1", value: "26"}, {id: "2", cr ...

The NextJS homepage and API endpoint are combined on a single page

In my Next.js application, I have multiple pages and I want the component loaded at http://localhost:3000/someEndpoint to be exactly the same as the one loaded at http://localhost:3000/ I have already created an index.js file, but I am unsure how to creat ...

Using Angular to dynamically access component properties

Seeking assistance with creating dynamic Tabs in TabView of PrimeNG. The components are displaying properly, but I am unsure how to access their properties. I am following the guidelines provided at https://angular.io/guide/dynamic-component-loader and us ...

Learn how to transfer and retrieve data in a different jade template using Node.js without relying on session management or query strings

I am currently facing an issue where I need to redirect and send data from one view to another in a single step using Jade templates. The code snippet below shows my attempt: customer.js var express = require('express'); var router = express.Ro ...

Improve code efficiency by streamlining a function and using more effective syntax techniques

I've been learning how to condense code with jQuery. Can this script be written in a more concise manner without everything being on one long line? items.push('<li id="' + key + '">' + ' (key: ' + key + ')&apo ...

Leveraging regular expressions for image domains within NextJS next.config.js

Is it possible to use regex in next.config.js to allow image domains? Giphy uses different numbers for its endpoints (e.g. media0.giphy.com, media2.giphy.com), but my regex isn't working and I'm seeing this error message: hostname "media0.gi ...

Issue with the functionality of Material-ui tooltip

I'm exploring the implementation of the material-ui tooltip feature and I am hoping to have it displayed at the top of the element. Despite specifying placement="top", the tooltip still does not appear as intended. You can view a demo of this issue b ...

exploring vue 3 table interaction using key events

I am facing an issue in Vue where key events are not being triggered. I have tried binding a listener on the body, but for some reason the @keypress event is not working as expected (I click on a row and then try to catch 'ArrowUp', 'ArrowDo ...

What is preventing obj from being iterable?

When I try to compile this code, an error appears stating that the object is not iterable. Why is this happening? My goal is to determine the number of users currently online. let users = { Alan: { age: 27, online: false }, Jeff: { age ...

Unable to run JavaScript file fetched from cache API

For a web application built using pure vanilla JavaScript without utilizing service workers, I am looking to cache a JavaScript file hosted on an AWS S3 file server explicitly. The script below will be embedded in the index.html file of the application (UR ...

Issue encountered with the openpgpjs example: `'The function openpgp.encrypt is not defined'`

I encountered an issue with the 'openpgp.encrypt is not a function' error while attempting to follow the sample provided on the openpgp.js github page: https://github.com/openpgpjs/openpgpjs/blob/master/README.md#getting-started After following ...