What is the best way to access data stored in the state of the store.js within a Vue application?

Currently, I am working on my initial project using Vue.js. The application involves a multi-step form that shares a common header and footer. As the user progresses through each step, the data entered is sent to store.js for storage. However, I have encountered an issue where I cannot retrieve the information from the earlier sections of the form to display a summary at the final step.

Every time I click on the "Next" button in each step, the data is sent to store.js and the navigation moves to the next component. Below is an example of this action within one of the components:


onSubmit() {
    const formData = {
        selectedService: this.focusService,
        selectedItem: this.selectedItem,
        selectedShop: this.selectedShop,
        selectedItemId: this.selectedItemId
      };
      
      this.$store.dispatch('formInfo', {
        selectedService: formData.selectedService,
        selectedItem: formData.selectedItem,
        selectedShop: formData.selectedShop,
        selectedItemId: formData.selectedItemId            
      });
      
      this.$store.dispatch('setStep', this.step + 1);
      this.$router.push('/shop/buyer');
}

In store.js, I verify if the data is correctly received by the 'formInfo()' method and then store it in a declared state class property. Additionally, I set up a getter to retrieve the stored information from the state:


export default new Vuex.Store({
  state: {
    // State properties here
  },
  actions: {
    formInfo({commit, dispatch}, authData) {
      console.log(authData)
      this.fisrtStepInfo = authData
      console.log(this.fisrtStepInfo)
    }
  },
  getters: {
    formInfoFirstStep (state) {
      console.log(state)
      return state.fisrtStepInfo
    }
  }

Lastly, in the component where I need to display this information in my HTML, I utilize the 'computed' section of my script to call the previously declared getter from store.js:


export default {
    data() {
        return {
          // Data properties here
        }
    },
    computed: {
        firstFormInfo() {
          console.log('firstforminfo')
          return !this.$store.getters.formInfoFirstStep
        },
    }
}

Despite setting up everything correctly, it seems like the getter is not being accessed in the 'computed' section. Any guidance on what could be going wrong would be greatly appreciated. Thank you for your time and assistance!

Answer №1

Actions are akin to mutations, with a key distinction: Instead of directly changing the state, actions commit mutations.

It's important to commit a mutation rather than modifying state directly:

  state: {
    ...
    formDetails: {}
  },
  mutations: {
    updateFormDetails: (state, data) => state.formDetails = data;
  }
  actions: {
    processForm({commit, dispatch}, formData) {
      console.log(formData)
      commit('updateFormDetails', formData)
      console.log(this.formDetails)
    }
  },
  getters: {
    getFormDetails (state) {
      console.log(state)
      return state.formDetails
    }
  }

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 you explain the purpose and function of stub.callsArg(index) feature in Sinon.JS?

Confusion has set in as I try to make sense of this. According to the documentation: stub.callsArg(index) - This command prompts the stub to execute the callback function found at the specified index. For instance, using stub.callsArg(0); will trigger the ...

How to pass route parameters using v-link in Vue Router

Within the Parent.vue file, I have included this anchor tag: <a v-link="{ path: '/somepath/somesubpath', query: { messageId: 999}}"> Here </a> And also this one: <a v-link="{ path: '/somepath/somesubpath', params: { me ...

Generate an interactive pie chart with visually appealing animations using jQuery, without any actual data

My task involves creating a pie chart to visually display different categories. However, the challenge is that the chart does not contain any data, ruling out options like Google charts or other data-driven chart makers. As a solution, I have turned the pi ...

Increase the gap between the legend and the chart when utilizing charts.js

I'm currently working on a project using charts.js and running into a slight issue. The legend for my bar chart is overlapping with the values displayed. I've been attempting to troubleshoot this problem without much success so far, so I would g ...

Video texture incorporated into Three.js

I'm currently experimenting with using a specific section of a video as a texture on a Three.js mesh. The video in question can be found at this link: . It features a fisheye lens, and I am only interested in incorporating the central circular portio ...

Passing variables from ExpressJS to JavaScript can be a seamless process

I am struggling with this issue; I am utilizing NodeJS to retrieve a JSON and I must transfer the variable to my page for use by JavaScript. app.get('/test', function(req, res) { res.render('testPage', { myVar: 'My Dat ...

Converting JSON data to an array using an Ajax request

I am currently working on an HTML project where I have the following code: <div id="main"> <div id="blogcont"> <p></p> </div> <button class="nvgt" id="prev" >Previous</button> <button ...

Switching my Selenium code to HtmlUnit: A Step-by-Step Guide

Currently, my Selenium code is working perfectly fine. However, I am looking to convert this code into HtmlUnit. I know I can use the HtmlUnitDriver like WebDriver driver = new HtmlUnitDriver(); I want to make it purely HtmlUnit. Below is the code that I ...

Error encounter when loading the chunk for FusionCharts's overlappedbar2d.js in React.js: fusioncharts.overlapped

Currently, I am working on a web application that utilizes next.js and FusionCharts. Within the app, various FusionChart types have already been set up. My task now is to integrate the Overlapping Bars chart as outlined in the following documentation: How ...

Is it possible to manipulate elements within an overflow container using JavaScript/jQuery when using the HTML style "overflow:hidden"?

My <div> has a styling of style="overflow:hidden" and the size of the <body> is fixed, intended as a multi-screen display without a user interface. Is there a method to access these "invisible" elements to identify the first one that exceeds t ...

Maximizing PUT Methods in HTTP RESTful Services

I've been playing around with my routes file and I'm looking to switch up the method being called (delete instead of update). Code Snippets: # User management API GET /users @controllers.Users.findUsers POST /user ...

Navigate directly to a child component in Vue, even when the parent component has a parameter

Recently, I have been delving into the world of Vue with TypeScript and I must admit, it has been quite an awesome experience so far. However, as I started learning about Vue routing, a question popped up in my mind that I just can't seem to find a sa ...

Can you identify the variances in the React codes provided? Is one more optimized or impactful than the other, or do they essentially perform the same function?

Currently working on a project where I have two different sets of code and I'm curious about the differences between them. Using ReactJS (latest version) Set 1: columns.map(v => v.aggregate = (values) => values[0]); Set 2: columns = columns ...

How can we delay UI updates until API calls have finished processing a chunk of requests in Redux-Saga without affecting the responsiveness of the user interface?

function* fetchDataFromChunks(dataList = []) { const segmentedData = yield call(splitDataIntoChunks, dataList, 5); for (let chunk of segmentedData) { const requests = chunk.map(item => call(retrieveImageData, item._id, item.im ...

When using Thunderbird Webextensions, calling .messages.getFull() may result in the Exception 0x80004005 being raised, specifically indicating

This question is a follow-up to a previous question/answer found at: In this scenario, the code attempts to retrieve a list of accounts, select the emailAccountName, get a MessageList object from the specified wantedMailFolderType, and then access a Messa ...

Guide to adding a checkbox to a JavaScript list

I'm currently working on building a task list using JavaScript. The concept is to type something into the input field and then, when the user clicks the button, a checkbox with that text will be generated. However, I'm facing an issue as I am no ...

The website flickers in and out as it loads

My site keeps flashing whenever it loads. Despite trying the solutions recommended in this stackoverflow post, I have had no success. Every page on my website loads a nav.html file using this code: $.get("nav.html", function(data){     $("#nav-placeho ...

Tips for confirming date is earlier than current date in Reactjs?

Looking for guidance on how to ensure a date selected by a user is always before the current date when using Material UI in my project. For instance, if it's January 6th, 2021 and the user selects either January 5th or 6th that would be acceptable. Ho ...

HTML and JavaScript - Facing issues rendering HTML content during the conversion process from Markdown format

In this particular scenario, my goal is to transform the content inside #fileDisplayArea into markdown format. However, I am encountering an issue where the HTML code within the div element is not being rendered. <div id="fileDisplayArea"># Title ...

Updating route from action within Vuex Store

Exploring ways to trigger a route change from the store. I attempted to import router directly into the store and use the following code: LOG_OUT({commit}){ commit('LOG_OUT__MUTATION'); router.push({ name: 'Login' }) } Unfo ...