Accessing state in Vuex modules is crucial for managing and manipulating data effectively

Feeling a bit lost here... I'm utilizing Vuex in my project and have a module called common stored in the file common.js:

const initState = {
  fruits: []
}
export default {
  state: initState,
  mutations: {
    SET_FRUITS(state, fruits) {
      console.log(fruits);
      state.fruits = fruits;
    }
  },
  actions: {
    async getFruits({ commit }) {
      const fruits =[
        {
          text: 'Apple',
          value: {id: 1, val: 'apple'},
        },
        {
          text: 'Banana',
          value: {id: 2, val: 'banana'},
        },
        {
          text: 'Pear',
          value: {id: 3, val: 'pear'},
        },
        {
          text: 'Plum',
          value: {id: 4, val: 'plum'},
        }
      ];

      commit('SET_FRUITS', fruits);
    }
  }
}

Now, let's take a look at my store defined in index.js:

import Vue from 'vue';
import Vuex from 'vuex';
import common from './modules/common';

Vue.use(Vuex);

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

I've attempted to access state.fruits within App.vue:

<template>
  <div>
    {{ this.$store.state.fruits }}
  </div>
</template>

<script>
export default {
  name: 'App',
  components: {
  },
  async mounted() {
    await this.$store.dispatch('getFruits');
    console.log(this.$store.state.fruits);
  },
}
</script>

The console.log output from mutations displays the array of fruits correctly. However, the one from mounted() function in App.vue returns undefined. What could be causing this issue? What am I overlooking?

Answer №1

Below is a practical demonstration. Make sure to review your vuex store setup and registration, and remember to utilize the dispatch method.

const store = new Vuex.Store({
  state: {
    fruits: []
  },
  actions: {
    getFruits({
      commit
    }) {
      const fruits = [{
          text: 'Apple',
          value: {
            id: 1,
            val: 'apple'
          },
        },
        {
          text: 'Banana',
          value: {
            id: 2,
            val: 'banana'
          },
        },
        {
          text: 'Pear',
          value: {
            id: 3,
            val: 'pear'
          },
        },
        {
          text: 'Plum',
          value: {
            id: 4,
            val: 'plum'
          },
        }
      ];

      console.log(fruits)

      commit('SET_FRUITS', fruits);
    }
  },
  mutations: {
    SET_FRUITS(state, fruits) {
      state.fruits = fruits;
    }
  },
});

new Vue({
  el: "#app",
  store,
  computed: {
    fruits() {
      return this.$store.state.fruits;
    },
  },
  mounted() {
    this.$store.dispatch('getFruits')
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.5.1/vuex.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id='app'>
  <div v-for='(fruit, i) in fruits' :key="i">
    {{fruit}}
  </div>
</div>

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

The elastic image slideshow maintains the original size of the images and does not resize them

When utilizing the elastic image slider, I encounter a similar issue as described at Elastic Image Slideshow Not Resizing Properly. In the downloaded example, resizing the window works correctly. However, when trying to integrate the plugin with Twitter B ...

Utilizing VueX Getter to extract distinct identifiers from an array

I need help filtering an array of objects to only retrieve messages with a unique correspondence_id. The data structure of the messages in the array is shown in this image. Here is the getter function where I want to implement the filter: getCorresponde ...

Is there a way to dynamically modify the email content with the Gmail API using JavaScript?

I have received the message body and now I need to make some updates to it. When I try using this login/code, I encounter a 400 error. I believe the issue lies in the body parameter of the request. Can someone please assist me with this? var token = loca ...

Having difficulty implementing a personalized color scheme for the mui component

Attempting to set the background color as midnightBlue but encountering an error: Error: Cannot read properties of undefined (reading '100') Upon reviewing the syntax, no errors were found. Perhaps this issue stems from a dependency problem? ...

The Autocomplete feature in Material-UI is not rendering any output

Within the render method of a class, an Autocomplete component is causing nothing to appear as rendered; once removed, everything else renders as expected. export default class Home extends Component { render() { return ( ... ...

Is it possible to pass a parameter to a PHP controller using JavaScript without relying on jQuery or AJAX?

Is it possible to achieve the task at hand? That's the main question here. My goal is to extract data from a popup window and then, upon closing it, send this extracted content to a PHP controller for further processing. I'm facing conflicts wi ...

Positioning a div to the right of another div within a container (box)

I'm currently trying to line up two divs alongside each other within a box. Using angularJS, I am dynamically generating input boxes and looking to include an image for the delete option next to each input box. Despite using "display: inline-block", I ...

modify the color of a box within a grid upon clicking it

I am curious if it is possible to change the color of a box when it is clicked. I am working on coding a "calculator layout" and would like to start with this part 1 2 3 4 5 6 7 8 9 0 This is what I have been working on and struggling with. $(docume ...

Setting the selected option of a select form element dynamically in Vue 3

Is there a way to dynamically set the selected option in Vue 3 when the data value doesn't match any available option value? Situation: If Florida (FL) is the stored state value and the country changes from United States (US) to Canada (CA), the Sta ...

Connect an EventListener in JavaScript to update the currentTime of an HTML5 media element

*update I have made some changes to my code and it is now working. Here's the link: I am trying to pass a JavaScript variable to an HTML link... You can find my original question here: HTML5 video get currentTime not working with media events javscr ...

Confirm that only the days of the present month are eligible for selection

I have been given the responsibility of validating a date field that is populated when an invoice is created. The date field consists of a text box and three button objects allowing users to select a date from a calendar, input today's date, or remove ...

Retrieve the fully loaded webpage source code in Java as it is displayed by the browser

There are certain webpages that utilize JavaScript and AJAX calls to populate fields during or after the page has loaded. An example can be found at this link, where the content in a size dropdown box is filled using JavaScript. I am wondering if it is po ...

Unable to mark checkboxes in Bootstrap 4 Dropdown (triggered by vue.js) due to unresponsive behavior

When using Vue.js to open a Bootstrap Dropdown, I encountered an issue with selecting custom checkboxes within the dropdown menu. I have come across information about event.stopPropagation() potentially causing this problem, but I am unsure where to imple ...

Randomly undefined custom jQuery function

Appreciate your assistance in advance. I am facing a peculiar scope issue on a page where multiple charts are rendered intermittently. I have created a set of jQuery functions to display different types of charts based on the provided options. Each funct ...

Incorporate the xml2js JavaScript library with Angular 2 for enhanced functionality

I've been attempting to utilize xml2js as an XML parser within my Angular 2 (RC 1 with TypeScript) web application. Unfortunately, I've encountered several errors without finding a solution that works. Here is the detailed process I followed: ...

Searching through the Symfony2 database with the help of Select2 and Ajax

Currently, my FAQ System is running smoothly. However, I am looking to enhance it by adding a search function using Select2. Here's what I have so far: Select2 AJAX Script <script> $("#searchall").select2({ ajax: { ...

Error Encountered While Creating a Polygon Wallet on Fireblocks

After following the instructions from Fireblocks Docs, I successfully created a default wallet named "BTC_TEST" like this: enter image description here. However, when attempting to create a Matic wallet, I encountered an Axios Error. Despite Matic being a ...

It appears that the home page of next.js is not appearing properly in the Storybook

Currently, I am in the process of setting up my next home page in storybooks for the first time. Following a tutorial, I successfully created my next-app and initialized storybooks. Now, I am stuck at importing my homepage into storybooks. To achieve this, ...

jQuery Autocomplete - Showing array of options upon selecting input field in Internet Explorer

After encountering an issue with the autocomplete feature in a web application, I posted a question on Stack Overflow. The provided answer solved the problem in Chrome, but unfortunately, it did not work in Internet Explorer 8 or 9, and possibly earlier ve ...

NodeJs: Transforming strings into UUID v4 efficiently

Suppose I have the following string: const input = '83e54feeeb444c7484b3c7a81b5ba2fd'; I want to transform it into a UUID v4 format as shown below: 83e54fee-eb44-4c74-84b3-c7a81b5ba2fd My current approach involves using a custom function: funct ...