Access the state of a Vuex module within a different module's action

I'm feeling a bit lost when it comes to working with Vuex store components.

How can I access the state of another module? I've tried various methods to retrieve data from the store, but I always end up with an Observer object. What is the correct way to interact with this observer?

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

Whenever I try to directly access anything from this object using rootState.user.someVariable, I receive an undefined response.

Getting state from components is not an issue for me.

Edit. Add code

User module

import * as Constants from './../../constants/constants'
import * as types from '../mutation-types'
import axios from 'axios'

const state = {  user: [] }

    const getters = {
       getUser: state => state.user
    }

const actions = {
getUserAction ({commit}) {
    axios({method: 'GET', 'url': Constants.API_SERVER + 'site/user'})
      .then(result => {
        let data = result.data
        commit(types.GET_USER, {data})
      }, error => {
        commit(types.GET_USER, {})
        console.log(error.toString())
      })
  }
}

const mutations = {
 [types.GET_USER] (state, {data}) {
    state.user = data
  }
}

export default { state, getters, actions, mutations }

Mutations

export const GET_LANGS = 'GET_LANGS'
export const GET_USER = 'GET_USER'

Store

import Vuex from 'vuex'
import Vue from 'vue'
import user from './modules/user'
import lang from './modules/lang'

Vue.use(Vuex)    
const store = new Vuex.Store({
      modules: {
    user,
    lang
  }
})

Main app

import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store/index'

Vue.config.productionTip = false

    new Vue({
      el: '#app',
      router,
      store,
      template: '<App/>',
      components: { App }
    })

Lang module, where I am attempting to access the store

import * as types from '../mutation-types'
import {axiosget} from '../../api/api'    

const state = {  langList: [] }

const getters = {
  getLangs: state => state.langList
}

const actions = {
// these two actions give me similar results
  getLangsAction (context) {
    axiosget('lang') // described below
  },
  getAnotherLangsAction (context) {
    console.log(context.rootState.user) <---- getting an Observer object
  }
}

const mutations = {
  [types.GET_LANGS] (state, {data}) {
    state.langList = data
  }
}

 export default { state, getters, actions, mutations }

axiosget action, API module

  import * as Constants from './../constants/constants'
import store from '../store/index'
import axios from 'axios'

    export const axiosget = function (apiUrl, actionSuccess, actionError) {
      console.debug(store.state.user) // <---- obtaining an Observer object, as previously mentioned
      // should append user token to axios url, located at store.state.user.access_token.token
      axios({method: 'GET', 'url': Constants.API_URL + apiUrl 
 + '?access_token=' + store.state.user.access_token.token})
        .then(result => {
          let data = result.data
          // todo implement this
          // }
        }, error => {
          if (actionError && actionError === 'function') {
           // implement this
          }
        })
    }

Component that calls dispatcher. If I access the state via mapGetters in computed properties - there are no issues

<template>
    <div>
   {{user.access_token.token}}
    </div>
</template>

<script>
  import { mapGetters } from 'vuex'

  export default {
    name: 'ArticlesList',
    computed: mapGetters({
      user: 'getUser'
    }),
    created () {
      this.$store.dispatch('getLangsAction')
      this.$store.dispatch('getAnotherLangsAction')
    }
  }
</script>   

In this code snippet, my goal is to retrieve the user's access token on the main site after login, and all subsequent data manipulations will be carried out via the API host.

Answer №1

If you're looking to retrieve the userId attribute from the userDetails object within the Vuex store module user.js, here's how you can do it:

userDetails:{
  userId: 1,
  username: "Anything"
}

In your action, you can access it like this:

authenticateUser(vuexContext, details) {
  userId = vuexContext.rootState.user.userDetails.userId;
}

Remember to include the path to the store module file after rootState and before the file name user if it is nested in folders.

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

Ajax Form Submission

My query relates to a combobox I have integrated: <select id='addOPTION' onchange='fillADDid(this.value);'> <option value=0>Select</option> <option value=1>etc</option> <option value=2>etc</option ...

If there is an error in retrieving data from the PHP file using `$.getJSON

Currently, I am integrating JSON into my login script and have included the following code snippet: $.getJSON("link to PHP where to get the JSON data from", function (data) { // THE CODE TO BE EXECUTED }); My question is, what is the most efficient way t ...

The regular expression used for validating domains does not function properly in the Safari browser

I am struggling with a JavaScript regular expression error that Safari is giving me. I am trying to validate a domain, but for some reason, this specific part (?<!-) is causing the issue because the domain name should not end with a hyphen. ^((?!-)[A-Z ...

Using AJAX to submit a PHP form without refreshing the page

Currently, I am facing an issue with my PHP and AJAX code for posting data without redirecting the page. Surprisingly, the script works perfectly on the login page but not on other pages. The main difference I observed is that the login page uses if (empty ...

Using jQuery to specifically target elements of a specific class that are nested within another element

I am currently using a jQuery function that toggles a drop-down navigation menu by changing its class when clicked: $(function () { $('.nav-titles').on('click', function() { $('.nav-dropdown').toggleClass(& ...

If I use npm install to update my packages, could that cause any conflicts with the code on the remote server?

As I navigate through the numerous issues, I stumbled upon the command npm ci that is supposed to not change the package-lock.json file. However, when I attempt to run npm ci, it fails: ERR! cipm can only install packages when your package.json and package ...

Utilizing external libraries in Vue 3 CLI projects

I've been attempting to load modules like Jquery and @tensorflow/tfjs, but I'm having trouble getting them to work. Both have been installed using npm. Everything in my @vue3/cli project works perfectly until I try to import these two modules. ...

A guide to iterating over a basic JSON structure using JavaScript

While there are similar inquiries on this topic within the site, they all involve arrays nested inside other arrays. I am struggling with a simpler issue and need some guidance. The JSON data is being produced by a PHP file and appears like this when retr ...

Enhance the readability of your Angular/Ionic applications with proper hyphenation

In my Ionic 3 app, I am using an ion-grid. Some words do not fit within the columns and are cut off, continuing on the next row without any hyphens added for proper grammar context. See image https://i.stack.imgur.com/3Q9FX.png. This layout appears quite ...

Generate a new structured Record / Object using the keys from an existing one using code

Within my TypeScript program, I have defined two base types (Player, State) and a few nested Record types that serve as mappings. Using a typed function, an instance of one of these records is created based on an existing instance of the nested record. t ...

The presence of an additional bracket is being triggered by the JSON array following

Currently, I am developing a function in Freemarker to iterate through all selected checkboxes and then display the same response on the form itself. The form is structured in Freemarker format, and I am utilizing JavaScript to create separate arrays for e ...

How can I maintain the selected state of checkbox and radio button in ReactJS after page refresh?

I am facing an issue with my multistep form that contains radio buttons and checkboxes from material UI. Although the data is stored correctly in state and local storage, when I move to the next page and then return, the selections appear unselected to the ...

The load function within THREE.FileLoader is specifically designed to retrieve the textual content of the index.html file

I've been working on a small web project using the create-js-app tool. I am attempting to load a file named test.txt from my src directory. Here is the code from my main.js file: import * as THREE from 'three'; const loader = new THREE.Fil ...

Load Vue dynamically to implement reCAPTCHA script

I am looking for a way to dynamically load a script like recaptcha specifically within the Register.Vue / login.Vue component. <script src="https://www.google.com/recaptcha/api.js?onload=vueRecaptchaApiLoaded&render=explicit" async defer> </s ...

Issues with the drop-down menu in the <s:select> element arise when attempting to set the

While utilizing a Map to populate the Struts2 tag <s:select >, I have noticed that when the form is submitted multiple times, a blank line is added at the end of the list. For example, if the Map contains 2 key-value pairs, it displays 3 records and ...

Issues with WebPack and Vue.js proxy configuration not functioning as expected on virtual machine

I am currently in the process of developing a website using vue.js on my Mac with the webpack-dev-server and Vue CLI. I am looking to fetch data from my backend, which is hosted on a Vagrant VM (local.dev), using Vue Resource. I attempted to set up a proxy ...

Is it necessary to make a distinct route for SocketIO implementation?

I am new to Socket.IO and I recently completed the chat tutorial in the documentation along with some additional tasks to gain a better understanding of how it works. Currently, I am attempting to establish a connection between a NodeJS server and a React ...

Executing a SQL query using a JavaScript variable as a parameter

I am currently working on a website form that includes a select menu populated with data from an SQL table using a loop. The form is being displayed using JavaScript scripts, which are functioning perfectly. However, I am facing an issue in the final step ...

Ways to center the percentage on the progress bar

I'm having an issue with positioning the percentage 100% in the center of the element. I attempted adjusting the spacing in the JavaScript code, but so far it hasn't been successful. Here is the current output for the code: http://jsfiddle.net/G ...

I am facing an issue where reducing the size of the renderer is causing my click events to be offset. What steps can I

At the moment, my rendered model (which is grey in color) stretches across the entire width of the html page with the mesh centered within that width. I want to reduce this width but when I do so, the click event on the model seems to be misaligned. Three. ...