Ways to retrieve the global state from within the mutation namespace module

Within my state, I have organized two namespace modules: portfolio and stocks. The structure looks like this:

export default new Vuex.Store({
  modules: {
    stocks,
    portfolio
  }
})

The stocks module contains a property called stocks, while the portfolio module contains a property called funds. I am attempting to utilize the BUY_STOCK mutation, which requires access to both stocks from the stocks module and funds from the profile module. In the profile module, I set it up as shown below:

"BUY_STOCK"(state, {stockId, quantity, stockPrice}) {
  console.log(state.stocks.stocks, state.portfolio.funds)
}

However, I ended up receiving undefined. This is because the state being referenced is merely the local module state. How can I gain access to the global state from within this mutation?

Answer №1

When working with Vuex actions, you have the ability to access rootState. Instead of directly calling a mutation, consider calling an action:

actions: {
 purchaseStock(context, {stockId, quantity, stockPrice}) {
    console.log(context.state.funds) // accessing local state
    console.log(context.rootState.stocks.stocks) // accessing stocks state via rootState
    // Next step is to invoke mutations using the obtained values 
    context.commit("PURCHASE_STOCK", {stockData, portfolioData}) 
  }
}

Answer №2

It appears that the profile module was not properly imported into the store/index.js file, which should include:

export default new Vuex.Store({
  modules: {
    stocks,
    portfolio,
    profile
  }
})

Furthermore, it would be beneficial to utilize getters in each module:

portifolio.js

export default {
  state: {
    funds: 'Some funds'
  },
  getters: {
    funds(state) {
      return state.funds
    }
  }
}

stocks.js

export default {
  state: {
    stocks: 'Some stocks'
  },
  getters: {
    stocks(state) {
      return state.stocks
    }
  }
}

You can now access them from the profile module as follows:

profile.js

export default {
  actions: {
    BUY_STOCK({ getters }, { stockId, quantity, stockPrice }) {
      console.log(getters.funds, getters.stocks)
    }
  }
}

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

Creating a mandatory 'Select' dropdown field in Vue.js

Hello, I am a beginner in VueJS and I am trying to make a select element from a drop-down list required. I attempted to add the required attribute as shown in the code below. Any suggestions on how to achieve this? Thanks. <v-select ...

What is the best way to display my table?

In the index.php view, you will find my table located <table class="striped"> <thead> <tr> <th>Id</th> <th>Name</th> <th ...

Allow the NodeJS application to conduct self-updates using the NPM package manager

Hello, I'm currently exploring ways to add unique functionality to my NodeJS application, but I'm encountering some challenges. What I aim to achieve is as follows: I am interested in implementing a server code update feature from the client si ...

Having trouble determining why the design is not displaying correctly

I'm currently working on a calendar webpage, and everything looks perfect until I add the new JavaScript element. Suddenly, the numbers in the first row start behaving strangely. I've tried to troubleshoot but can't seem to figure out what&a ...

Broadcast to every socket except the one that is malfunctioning on Socket.io

My current task involves sending a message to all connected sockets on my server using socket.io. The code I have written so far looks like this: if(electionExists) { var connectedClients = io.sockets.adapter.rooms[electionRequested].sockets; ...

Utilizing JavaScript to Extract JSON Information from Knockout.js

Incorporating knockout into my project has been a great help as I retrieve JSON objects using Ajax. One question that arises is how to effectively utilize this data in my custom JavaScript code: After receiving the mapped item from the ajax call, here is ...

What crucial element is absent from my array.map function?

I have successfully implemented a table with v-for in my code (snippet provided). However, I am now trying to use Array.map to map one array to another. My goal is to display colors instead of numbers in the first column labeled as networkTeam.source. I at ...

What is causing it to give me 'undefined' as the result?

Trying to execute a script, test.al(); and within test.al, it calls getcrypt.php();. The php script is hosted on a webserver, and it is functioning properly. Here are the current scripts being used: JS var getcrypt = { php: function () { $.a ...

Load Angular scripts only when needed

I need to develop an application that can dynamically register new Angular Controllers obtained from a script. This application should load the minimum necessary scripts at startup and then fetch additional scripts as needed from other modules. Here' ...

Steps for Implementing a Delay on Bootstrap Dropdown Hover

Is there a way to create a delay for the bootstrap dropdown feature while ensuring that it still appears on hover? If you want to test this, click here: http://www.bootply.com/YcVBzvXqrR This is the HTML code I'm using: <div class="container"&g ...

Is there a method to programmatically identify enterprise mode in IE11?

Is it possible to detect Internet Explorer 11 Enterprise mode programmatically? This would involve detecting at the server side using C# or JavaScript/jQuery. The discussion on the following thread has not reached a conclusive answer: IE 11 - Is there a ...

What is the best way to use lodash to group objects that contain nested objects?

Currently utilizing Typescript in conjunction with Lodash! Upon retrieving data from the database, here is the resulting output: [ { "unitPrice": 0.01, "code": "92365524", "description": "Broto gr ...

Is it possible for a div nested within another div to still occupy space on the page despite being set

<html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript"> $("select#choosebook").change(function(){ $(".title").slideDown(" ...

The condition is not being recognized after clicking the third button

When the button is clicked for the first time in the code snippet below, all divs except for the red one should fade out. With each subsequent click, the opacity of the next div with a higher stack order should be set to 1. Everything works fine until the ...

Setting a single value for several identifiers within a JSON object

I'm new to JSON and I'm curious if it's possible to have a name/value pair with multiple names. Essentially, I want to be able to search for either name and retrieve the same value without having to update the value in two different places. ...

changing the name of a variable within ng-include

Here is some important HTML code: <ng-include src="'app/views/order.html'"></ng-include> Within the scope of this ng-include, there is a variable called trade. The structure of the trade variable is as follows: var trade = { or ...

What could be causing the delay in response times from these unpredictable APIs within the Express server?

We are currently experiencing performance issues with our Express.js server and MongoDB database. Randomly, some API requests are taking too long to respond or timing out throughout the day. Our application is in production, hosted on two AWS instances wit ...

Is it possible to employ getBoundingClientRect() for several elements sharing the same class?

I'm in the process of implementing sticky navigation on my website that will dynamically change as users scroll through different sections. Specifically, when scrolling over a section marked with the class .dark, I want the logo and text color to swit ...

What is the best way to choose all elements that fall between two specific elements?

Looking to grab content situated between two specific elements within an HTML structure. The HTML snippet in question is as follows... <h2>This is firsty</h2> <p>Some para</p> <ul> <li>list items</li> <li&g ...

Mastering the Art of Tallying Select Choices in Protractor

Experiencing an issue with counting options in the select attribute during my test. Here is the code snippet: it('should verify the number of options', function()) { expect(element(by.id('sorting_options')).all(by.tagName('optio ...