The changes to variables are confined to the Vuex Store and do not affect the global scope

Issue Resolved: Incorrect Variable Being Used

I encountered an issue where I was unable to access a stored value after mutating it in a component. Initially, I would select an array of numbers from a list, which would then be stored in the store upon pressing a button. However, when attempting to retrieve the value from the store, it appeared empty.

Here is my Vue Component:

<template>
   <MultiSelect
        class="groupselect"
        v-model="localSelectedNumbers"
        :options="options"
        optionLabel="id"
        placeholder="Choose Devices"


    />
  <v-btn @click="refresh()">Click</v-btn>
  <p>{{selectedNumbers}}</p>
</template>
<script>
import MultiSelect from "primevue/multiselect";
import {mapMutations, mapState} from "vuex";

export default {
  name: "DeviceSelection",
  components: {MultiSelect},
  computed: {
    ...mapState([
        'mode',
        'selectedNumbers',
        'options'
    ])
  },
  data() {
    return {
      localSelectedNumbers: [],
      show: []
    }
  },
  watch: {
    selectedNumbers(newValue, oldValue) {
      this.show = newValue
    }
  },
  methods: {
    ...mapMutations([
        'setRows'
    ]),
    refresh() {
      this.setRows(JSON.parse(JSON.stringify(this.localSelectedNumbers)))
      //console.log(this.selectedNumbers)
    }
  }
}
</script>

Overview of My Store setup:

import {createStore} from "vuex";

const store = createStore({
    state() {
        return {
            options : [
                {id:1}, {id:2}, {id:3}
            ],
            rows: [],
            mode: false,
            selectedNumbers: []
        }
    },
mutations: {
        setRows(state, payload) {
            console.log(state.rows)
            state.rows = payload
            console.log(state.rows)
        },
}
export default store;

I have attempted various solutions including using watchers and manual refreshing. Despite seeing the correct output in the console log for the Store (with numbers 1 and 2), the `selectedNumbers` variable in the Vue Component remains empty as does `this.$store.state.selectedNumbers` when accessed within the component.

Answer №1

The mutation is currently updating the rows state, but you are calling selectedNumbers in the component. You should either update the selectedNumbers state in the mutation or call the rows state in the component.

Answer №2

The reason for the issue is because you are updating the rows in the mutation function, but your watcher is set on the selectedNumbers. I recommend making the following changes to your mutation:

mutations: {
  updateSelectedNumbers(state, payload) {
    console.log(state.rows);
    state.rows = payload.map(item => item.id);
    console.log(state.rows);
  },
}

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

Dealt with and dismissed commitments in a personalized Jasmine Matcher

The Tale: A unique jasmine matcher has been crafted by us, with the ability to perform 2 key tasks: hover over a specified element verify the presence of a tooltip displaying the expected text Execution: toHaveTooltip: function() { return { ...

Whenever I try to access a specific position within a JSON array, I receive the value of 'undefined'

After executing a database query in PHP and returning the results through AJAX in a JSON array, I am facing an issue where the data is being accessed as 'undefined'. Why is this happening? Below is my PHP code snippet: <?php $tipo_prod ...

having difficulty preserving the edited HTML document with JSoup and Java

I am facing an issue with modifying and saving changes to an existing HTML file. I can make modifications, but when it comes to saving the changes back to the HTML file, I encounter difficulties. https://i.sstatic.net/CRhUV.jpg The specific modification ...

What are the advantages of storing data in HTML tags that do not contain any content?

Is it considered poor practice to include an empty span in a template, or is there a more effective solution available? Is it acceptable to use a blank span tag like this within my code? <span class="stored-id-number" data-idnumber="1234"><!-- em ...

The value is not being populated in the text area when the onchange event occurs

<textarea className="form-control queryheight box_xp" placeholder="Enter Dashboard Content" type="text" onChange={this.dashboardtextchartchange.bind(this)} value={this.state.textdashboard}> </textarea> Function triggered on change : dashb ...

Sort a JSON object in ascending order with JavaScript

I have a JSON object that needs to be sorted in ascending order. [{ d: "delete the text" }, { c: "copy the text" }] The keys d and c are dynamically generated and may change. How can I sort this into? [{ c: "copy the text" }, { d: "delete the text" }] ...

Identifying all Images with JavaScript, Including Asynchronous Ones

Is it possible to use JavaScript to identify all images within a document, even those that are loaded asynchronously (possibly after the DOM is fully loaded)? I am interested in developing a function that can determine if Google Analytics has been loaded ...

How can I trigger HierarchicalDataSource.read() when the kendoDropDownList's change event is fired?

Currently, I am utilizing the treeview and HierarchicalDataSource features of KendoUI. Additionally, I have included a kendoDropDownList at the top of the page. Each time a user changes the value of the dropdown list, it triggers the 'change' eve ...

Navigating to collapsed b-element using the <a> anchor tag

My SVG element collapses a b-collapse element when clicked. I am trying to make the browser automatically scroll down to the newly displayed element. Currently, I have an anchor tag pointing to the id of my b-collapse element around the SVG element. The is ...

Assistance required in filling out a table solely through JavaScript with input from an HTML form

Hello, I am currently pursuing a second career and have just started learning HTML & JavaScript. For a simple assignment, I need to take user input in the form of numShares and numYears through HTML. My goal is to use JavaScript to populate a 3-column tabl ...

Make sure that when a user clicks on the back button in their web browser, it

Designing a file selection menu where users can choose a file and view it in a text area on a new page, allowing for text editing and saving with a click of a button. Users should be able to return to the file selection menu by simply clicking the browser ...

Despite calling this.setState to update my state, the render() method is still displaying the previous values

class EditLocation extends Component { constructor(props) { super(); this.state = { LocationId: '', locationOptions: [], } this.baseState = this.state; this.findLocationById = this ...

Using the Ajax method from a separate class in TypeScript: A step-by-step guide

Recently, I started learning about typescript and ajax. One of the challenges I encountered was while creating a method in typescript for making ajax calls that can be used across classes: myFunc(value: string): JQueryPromise<any> { var dfd = $. ...

Navigating the website with curtain.js and anchor tags

Currently, I am working on a website located at www.TheOneCraft.co.uk. I have incorporated the curtain.js jQuery plugin to create animated slide/pages as users scroll down. However, I have been unsuccessful in making the navigation bar follow this animati ...

Tips for making Google search results include query strings in the returned links

I need help figuring out how to make Google search results show a URL containing a query string. Here's an example from the project I am currently working on: Instead of this link, Google search returns: If anyone has any suggestions for fixing this ...

An angular function cannot be reinvoked depending on certain conditions

The concept is: Step 1: Click on the eye icon to close it: This will change the eye icon to an open eye. And reveal the password. Step 2: Click on the open eye icon: This will change the eye icon back to a closed eye. And hide the password. HTML: < ...

Guide for adding multiple markers on a Google map

Currently, I am facing a challenge with plotting multiple markers on a Google map and need some assistance. The longitude and latitude of the locations are extracted from JSON data obtained through an AJAX API call. I have been referring to a particular p ...

Getting the most out of geometry vertices with Threejs: mastering partial transforms

In my current project, I am working with a mesh that consists of approximately 5k vertices. These vertices have been merged from multiple geometries into a flat array. Initially, I was able to modify individual vertices successfully by setting the flag `ve ...

What is the best way to display the absent months in a mongo aggregate query with a value of 0?

Is it possible to ensure that the missing months in the aggregate result have a BruteAmount value of zero? Purpose This code aims to generate two arrays containing the month names and their respective BruteAmounts. The data should be ordered by the curre ...

Utilizing TIMING=1 with eslint to evaluate rule efficiency on Windows operating system

On the official ESLint website, there is a section titled Per-rule Performance. It explains that "setting the TIMING environment variable will prompt the display of the ten longest-running rules upon linting completion, showing their individual runn ...