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

Unable to dynamically load a component into page.tsx within Next.js

When importing a component into another component there are no issues, but when trying to import a component into a page it results in an error... I am new to this so any help is greatly appreciated. This is how I am importing: const CodeSampleModal = dy ...

What is the best approach for dynamically appending new elements to a JSON array using PHP?

I am facing an issue with the JSON below: [{"username":"User1","password":"Password"}, {"username":"User5","password":"passWord"},] The above JSON is generated using the PHP code snippet mentioned below: <?php $username = $_POST["username"]; ?>&l ...

Adding a backslash in Angular: Tips and Tricks

I have a question about adding a backslash to a string that is returned from a div, for example Car1 \sold. Although I am able to retrieve the status, I am having trouble adding the backslash. Here is what I have tried so far: <span>{{addBackl ...

When choosing the child option, it starts acting abnormally if the parent option is already selected in Angular

I am encountering an issue while trying to select the parent and its children in the select option. The concept is to have one select option for the parent and another for the child. I have parent objects and nested objects as children, which are subCatego ...

Efficiently handle user authentication for various user types in express.js with the help of passport.js

Struggling to effectively manage user states using Passport.js in Express.js 4.x. I currently have three different user collections stored in my mongodb database: 1. Member (with a profile page) 2. Operator (access to a dashboard) 3. Admin (backend privi ...

gulp - synchronized gulp.pipe(gulp.dest) execution

Here's my challenge: I have two tasks, where Task B depends on Task A. In Task A, one of the requirements is to loop through an array and then use gulp.dest, but it seems like Task B will be executed before Task A is completed. The main goal of Task ...

Initiate a POST request to download the file upon clicking the button

How can I initiate a file download when a button is clicked? During testing, I noticed that sending a GET request using <Link href="/api/generate-pdf"> works perfectly and the PDF file gets saved. However, when I use a button to hit the API, the dow ...

Utilizing ReactJS and Gatsby Js: How to pass the value of a child component to the parent component to create a button

In my current project, I am facing an issue with a simple component that is supposed to pass back the link value from the child component to a function in the parent component. However, it seems to only call back the full function instead of its actual v ...

Development and staging setups tailored specifically for a JavaScript SDK

Currently, I am working with a Javascript SDK that is available on NPM. Alongside this, I have a Vue application utilizing the SDK and it's crucial for me to test them together across various pre-production environments (such as staging). Here are the ...

Using jQuery's .each() method to iterate over a JSON object may only display the

Running into some trouble with jQuery.each(). I'm pulling JSON data from another PHP file and trying to display a specific key value from it. This is the JavaScript code I have: <div class="row" id="fetchmember"> <script type="text/javasc ...

Determine whether a click event originated from within a child window

Currently, I am utilizing window.open to initiate a new window in javascript and my goal is to identify clicks made within the child window. Essentially, if a click event occurs in the child window, I aim to modify the parent window accordingly. I have a ...

Is it possible to postpone sending a message on Discord until a certain event has been successfully completed?

After the User leaves the Discord, I attempted to create a RichEmbed Message that would include a random GIF from Giphy. The GIF was meant to be generated using the getGiphyPic() function with the help of this node module: https://github.com/risan/giphy-ra ...

What is the reason for jquery requiring _$ when overwriting?

var // Optimizing references to window and allowing renaming window = this, // Increasing efficiency in referencing undefined and enabling renaming undefined, // Creating aliases in case of jQuery overwrite _jQuery = window.jQuery, // Creating aliases in ...

Progressively updating elements one by one leads to updates

I am currently working on a webpage where one element ('.item--itemprice') updates its text through a function that I don't want to modify. My goal is to have another element ('.header--itemprice') update its text to match the firs ...

NextJS - Accessing local files with readdir and readFile functions leads to error: Module not found when trying to resolve 'fs' module

I have been working with NextJS and have successfully used the getStaticProps functionality in previous projects to populate data. However, I recently set up a new NextJS project and it seems that this functionality is no longer working. When starting th ...

Searching for a streamlined approach to sending out numerous HTTP requests in a node.js environment

I'm new to the world of JS/node.js after working with .Net. I have an existing Web API host that I want to stress test with different payloads. I am aware of load testing tools available for this purpose, but my focus right now is on finding an effic ...

The tsconfig.json file is located separate from the project directory

Working on my project called "portal" has been quite an interesting journey. As I delved deeper into development, I realized the need for multiple projects within the repository. This led me to restructure my project setup like this: A question popped up ...

Fixed position scrollable tabs with Material UI

I recently implemented material-ui scrollable tabs in my project, referencing the documentation at https://mui.com/material-ui/react-tabs/#scrollable-tabs. Here is a snippet of the code I used: <Tabs value={value} onChange={handleChange ...

What methods are available for modifying nodes generated dynamically?

I have been on a quest for quite some time now to find a way to manipulate HTML content that has been dynamically added. Initially, I fetch a cross-domain website using getJSON: $.getJSON('http://whateverorigin.org/get?url=' + encodeURIComponent ...

Send the values of the form variables as arguments

I am trying to integrate a webform (shown below) with a function that passes form variables. Once the user clicks submit, I want the username and password to be passed into a website login function: $.ajax( { url: "http://microsubs.risk.ne ...