Ways to retrieve live data from vuex state directly into a component

I am currently delving into the world of Vuex, but I believe there are some fundamental concepts that I may be missing. Any suggestions or insights would be greatly appreciated.

Currently, I am dispatching the scale value of a zoomable map from one component to the Vuex store.

Within my Store.js file:

export default new Vuex.Store({

    state: {
        scale: ""
      },

    getters:{
       getScale: state => {
          return state.scale
        }
      },

     mutations:{
        setScale: (state, payload) => {
          state.scale = payload  
        }
      },

      actions:{  
        updateScale: (context, payload) => {
          context.commit("setScale", payload);
        }
      }    
})

This part seems to be functioning as intended, as I can see the scale number changing in the mutation, state, and getters sections when zooming in/out on the map with my mouse. However, I have encountered difficulties when attempting to retrieve this data from the Vuex state within another component.

In my Map1.vue file:

mounted(){
   var scale = this.$store.getters.getScale
}

Unfortunately, I am only receiving the value stored in the state property "scale" (in this case, an empty string). My intention is to access the dynamically updated data that was sent to the state. Retrieving static data worked perfectly fine (I tested it with a simple array).

I also tried retrieving the data using a computed property, but encountered a similar issue where only the initial scale value was being accessed within mounted:

computed: {
  scaleValue(){
     return this.$store.getters.getScale
    }
}

mounted(){
  var scale = this.scaleValue
}

I seem to be at an impasse. Based on my research, it appears that whenever I scroll the map using my mouse, the data is sent to the action for processing, then stored in the state via mutation. Shouldn't I be able to access this updated data (such as the scale) from any other Vue component within my application?

UPDATE: I have included the Map1.vue component below for reference

<template>
  <svg-map name="Zupanije"></svg-map>  
</template>
<script>
import * as d3 from 'd3'
import SvgMap from "./SvgMap"
export default {
    name: "Map1",

    components: {
        "svg-map":SvgMap
    },
    mounted(){
        ......lots of JavaScript code
        .
        .
        var scale = this.$store.getters.getScale
    }
}
</script>

Answer №1

It seems that you may benefit from using a method such as watch

data: {
    scale: this.$state.scale
},
watch: {
    '$store.state.scale': (newVal) => {
        this.scale = newVal;
    }
}

Answer №2

Perhaps giving this a shot might shed some light on the issue. Have you considered trying this approach and checking the outcome? How do you typically trigger your action?

<template>
    <div>
        {{ MEASURE }}
    </div>
</template>


import { mapGetters, mapActions } from "vuex";
export default {
    ...mapGetters(["MEASURE"]),
}

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

Tips for selecting a radio button using its unique identifier

I'm having trouble getting this code to work properly. I can't seem to find any mistakes in the code, can someone please assist me in resolving this issue? <html> <body> <input type="radio" name="radio" id="radio1">Site 1< ...

How do I assign a background image to a rectangle using JointJs?

What is the best way to customize the background image of a rectangle in my JointJs project? ...

Switch on checkboxes using radio buttons

Expanding on the solution provided in this forum thread, I am attempting to implement a feature where a radio button can be used to toggle all checkboxes. When toggled, the checkboxes should be checked; when not toggled, they should remain unchecked or dis ...

Resolve the flexible width problem when inserting text in pptxgenjs

I am attempting to replicate a layout similar to this https://i.sstatic.net/HDUhV.png However, the text width is taking up more space than anticipated. https://i.sstatic.net/CnKIB.png The current text behavior resembles that of a div, but I would like ...

Guide to setting up a nested vuetify navigation drawer

I am facing a scenario where I have one fixed navigation drawer with icons and another dynamic navigation drawer that should open and close adjacent to the fixed one without overlapping. The current implementation is causing the dynamic drawer to overlap t ...

Sending JSON data back to the server using KeyValuePair in C#

My goal is to send my JSON list back to the POST method (EditCompanyReportField) on the C# server side. The related parameter (fieldSorted) in my method is an array object, but the values are not being passed through. I have a few question marks regarding ...

Creating a dynamic data filter for a table dynamically

I am seeking help with an issue I've been struggling with for the past week. I am attempting to add a feature that allows the filtering of items based on vendor names. Here are the steps I need assistance with: Retrieve all vendor names from the dat ...

Having trouble loading the jade view in express

I am having trouble with creating a jade view and loading it using express. The path / works fine, but when I try to load helloworld, the browser returns an error saying Cannot get /helloworld. This is the view I have created and saved in the views folder ...

What are the steps to utilize the `<script setup>` feature?

Vue version: 3.0.11 Here is the code snippet: <template> <button @click="inc">{{ count }}</button> </template> <script setup> import { ref } from 'vue' export const count = ref(0) export const i ...

How to activate a hyperlink without being taken to a new page

I have a variety of products stored in a mySQL database, and I am currently retrieving their links through the use of $producturl in my script. These URLs are designed to add the product to the shopping cart (http://www.example.com/cart/?add-to-cart=1127). ...

Delivering a static Angular app through an Express Server

In my current setup, I have an Angular app being served as static content in an Express Server. When Express serves static files, it automatically adds an ETag to them. Subsequent requests will then check if the ETag matches before sending the files agai ...

How can I use jQuery to switch the positions of two <div> elements in HTML based on the selection of a dropdown value?

I need to switch the display positions of two <div> containers based on a dropdown value change. Can this be accomplished using jQuery? Here are the two div containers whose display positions need to be interchanged: <div id="first"><p> ...

Using a loop to incorporate numerous objects in three.js - inserting both .obj and .mtl files in bulk

I've encountered an issue in my code where I'm unable to locate the mistake(s)... The problem lies within a loop that loads multiple objects and assigns them names, but the "objects" array remains empty as a result. My goal is to give each object ...

Solving the Dilemma of Ordering Table Rows by Value in JavaScript

I am currently working on a table and my goal is to display rows in an orderly manner based on the sum of their columns. Essentially, I want the rows with the highest values to be displayed first, followed by rows with second highest values, and so on. Des ...

Why does Laravel DatePicker consistently default to showing the previous month instead of the selected month?

I've hit a roadblock trying to pinpoint the source of this error in the Tailwind UI Datepicker. Whenever I choose 09-08-2021 on the visual Datepicker, the value ends up saving as 09-07-2021. I've researched similar cases where the month value re ...

Vue Dynamic Table Title

Is it possible to add labels to a pivot-table in Vue without affecting array indexes and drag-and-drop functionality as shown in the screenshot below? https://i.stack.imgur.com/5JTSM.png Are there alternative methods for implementing this feature? You c ...

Troubleshooting Cloud Functions: Fixing functions.logger.log not Functioning

Whenever a user updates the chat/{id} documents, this function is triggered. const functions = require("firebase-functions"); exports.onChangedChat = functions.firestore .document('chat/{id}') .onWrite((change, context) => { fun ...

Tips for implementing File upload with WEB API in Dot net core

Currently, I am developing an ASP DOT NET core web api that requires sending multiple attachments. My implementation looked something like this: <input type="text" id="txt_firstName" /> <input type="text" id="txt_lastName" /> <input type= ...

Dynamically Exporting Node Modules

// custom-exports.js exports.createCustomExports = (exportObject) => { module.exports = exportObject for (const exportItem in exportObject) { exports[exportItem] = exportObject[exportItem] } } // calculations.js const { createCustomExports } = ...

Firestore query failing to retrieve most recent data

I have implemented a route guard in Angular that validates a specific value in firestore before granting access to the designated route. The component is accessed only after an HTTP cloud function has finished executing. This cloud function generates an o ...