vue mapGetters not fetching data synchronously

Utilizing vuex for state management in my application, I am implementing one-way binding with my form.

<script>
  import { mapGetters } from 'vuex'
  import store from 'vuex-store'

  import DataWidget from '../../../../uiComponents/widget'
  export default {
    data () {
      return {
        isEdit: false,
        msg: {
          id: 0,
          content: '',
          isEnabled: false
        }
      }
    },
    components: {
      DataWidget
    },
    computed: mapGetters({
      messageId: 'messageId',
      messageContent: 'messageContent',
      isMessageEnabled: 'isMessageEnabled',
      isMessageValid: 'isMessageValid'
    }),
    methods: {
      onSave () {
        store.dispatch('saveMessage', this.msg, { root: true })
        if (this.isMessageValid) {
          this.isEdit = !this.isEdit
        }
      }
    },
    created () {
      this.msg.id = this.messageId
      this.msg.content = this.messageContent
      this.msg.isEnabled = this.isMessageEnabled
    }

  }
</script>

<b-form-textarea id="content" v-model="msg.content" :rows="3" required aria-required="true" maxlength="250"></b-form-textarea>

Upon loading, the values in created() are not bound until an action is performed on the page or a refresh occurs.

I have attempted using mounted() but encountered the same issue.

This is how my Vuex store (Message Module) is structured:

const state = {
  messageId: 0,
  messageContent: '',
  isMessageEnabled: false,
  isMessageValid: true
}

const getters = {
  messageId: state => state.messageId,
  messageContent: state => state.messageContent,
  isMessageEnabled: state => state.isMessageEnabled,
  isMessageValid: state => state.isMessageValid
}

const actions = {
  getMessage ({commit, rootGetters}) {
    api.fetch('api/Preference/Message', rootGetters.token)
    .then((data) => {
      commit(types.MESSAGE_LOAD, data)
    })
  }
}

const mutations = {
  [types.MESSAGE_LOAD] (state, payload) {
    state.messageId = payload ? payload.id : 0
    state.messageContent = payload ? payload.content : ''
    state.isMessageEnabled = payload ? payload.enabled : false
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}

I also have a global action (action.js) that retrieves multiple data:

export const loadSetting = ({ commit, rootGetters }) => {
  api.fetchAsync('api/Preference/all', rootGetters.token)
  .then((data) => {
    commit(types.MESSAGE_LOAD, data.message)
    commit(types.HELPDESK_LOAD, data.helpDesk)
    commit(types.VOLUME_LOAD, data.volumes)
    commit(types.DOWNLOAD_LOAD, data.downloadService)
  })
}

My API call function:

  async fetchAsync (url, token = '') {
    let data = await axios.get(HOST + url, {
      headers: {
        'Authorization': 'bearer ' + token
      }
    })
    return data
  }

Answer №1

The issue arises when an async method is called in Vuex but treated as a synchronous operation in the created method, leading to an expectation of immediate value retrieval.

To address this, it's essential to utilize the reactive nature of computed properties for automatic updates on any changes. To achieve this, modify the computed property setup as follows:

    computed: {
       ...mapGetters({
          messageId: 'messageId',              
          isMessageEnabled: 'isMessageEnabled',
          isMessageValid: 'isMessageValid'
        }),
        messageContent(){
            get () {
               return this.$store.getters.messageContent
            },
            set (value) {
               //this is just an example, you can do other things here
               this.$store.commit('updateMessage', value)
            }
        }
    }

Subsequently, update the HTML code to incorporate the use of messageContent:

<b-form-textarea id="content" v-model="messageContent" :rows="3" required aria-required="true" maxlength="250"></b-form-textarea>

For additional guidance, please refer to: https://vuex.vuejs.org/en/forms.html

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

What is preventing HTML from triggering JavaScript when loaded inside a <div> with a script?

I'm working on creating a collapsible menu that I can easily customize on any page without the use of iframes. As someone new to web design, I have knowledge of CSS and HTML but I am currently learning JavaScript with limited experience in jQuery or A ...

Is it possible to set up VS Code's code completion feature to automatically accept punctuation suggestions?

For all the C# devs transitioning to TypeScript in VS Code, this question is directed at you. I was captivated by the code completion feature in VS C#. To paint a clearer picture, let's say I'm trying to write: console.log('hello') W ...

Clicking on the input triggers the appearance of a border using the OnClick function

I am currently developing my own website with a login feature that requires input tags of text-type. I would like to implement a functionality where clicking on these input tags will display a border, even when the mouse is not directly hovering over them. ...

Best Placement for Socket.io Server in WebStorm Express Template

Trying to integrate socket.io into an express server generated by WebStorm. Should the setup of the server and socket.on events all be placed inside /bin/www, or is it better practice to create separate controllers like index and users pages? PS: Another ...

Unable to retrieve information from the API server (with a public IP) using ngResource

This may seem like a naive question, but I am stuck and new to Angular. Despite searching extensively, I have not been able to find a solution. var app=angular.module('myApp',['ngResource']); app.controller('myCtrl',['$s ...

The PHP function is returning an undefined value in JavaScript

I feel like there must be a simple solution to this problem that I just can't seem to find. Everything related to PHP search functions and queries is functioning properly, except for the fact that the data isn't displaying correctly in the text a ...

Regular expression: match all content up to a certain word(s)

I have two different versions of a string that look like this: The Student's Companion *Author: Alcock, Pete;May, Margaret;Wright, Sharon*MIL EAN/ISBN: 9781283333115 Java Programming: Java Expert*Author:Sarang, Poornachandra*MIL EAN/ISBN: 978128011 ...

Having trouble getting JavaScript to select a stylesheet based on time?

I am attempting to implement two different styles based on the time of day. Here is the code I am using to select the CSS file depending on the current time: <script type="text/javascript"> function setTimedStylesheet() { var currentTim ...

The analytics event code is visible in the source code, but is not displaying in the console

I am facing an issue with a website built on Umbraco and it has me completely stumped. I have set up event tracking for Analytics on several download buttons, and while most of them are functioning properly, there is one button causing me trouble. When I ...

The challenges of deploying a Vue.js frontend with a Flask backend on Heroku

My current project involves a Vue.js frontend with a Flask backend as the REST API. The code is structured in client and server folders within my Github repository. I am attempting to deploy this web app on Heroku using the Github deployment feature, but e ...

Display information in a div container from other pages on the website

I am attempting to dynamically load content into a div in Index based on the selection made in a dropdown box, but it doesn't seem to be working correctly. I have created a simple example using four pages to demonstrate the issue: Index.html one.html ...

Utilizing jQuery to dynamically update background colors within an ASP repeater based on the selected value of a dropdown list

On my asp.net web page, I have a repeater that displays a table with various fields in each row. I am trying to make it so that when the value of a dropdown within a repeater row changes, the entire row is highlighted in color. While I have achieved this s ...

Achieving enlightenment with Satori in NextJS: Transforming SVG to PNG in a NodeJS Environment

I am currently exploring the capabilities of satori and integrating it into my next.js api routes. (I'm unable to utilize the vercel/og package). While I have successfully set everything up, I'm facing a challenge in converting the svg image gen ...

Creating a new object through manipulation of existing objects

In my attempt to transform an existing object into a new object structure, I am facing some challenges. Here is the current data set: const jsonStructure = { "a11/a22/animations": "snimations", "a11/a22/colours": "sl/colours", "a11/a22/fonts" ...

Changing the background image within a CSS class on an imported Vue component

Is there a way to dynamically change the background-image on a CSS class within an imported component? I have successfully installed 'vue-range-slider' and imported RangeSlider. The setup for the range-slider is as follows: <template> ...

Changing the hidden input value to the data-id of a selected <a> element

I've set up a form with a dropdown menu and subdropdowns, generated using a foreach loop through a @Model. When I click on one of the options, I want the value of my hidden input field to match the data-id of the clicked item. This is what I have in ...

How can I create a placeholder in semantic-ui components?

I'm currently utilizing the plugin and facing an issue with displaying the placeholder. Although data retrieval from the database is functioning properly, the placeholder is not being shown. Note:- When I remove the PHP code, the placeholder display ...

What is the best way to obtain the output produced by a function when a button is clicked

When I click on a button, the desired action is to trigger a function that adds a new property inside an object within a large array of multiple objects. This function then eventually returns a new array. How can I access and utilize this new array? I am ...

Having trouble getting a new input box to be added when clicking with AngularJS?

I am facing an issue with adding dynamic form fields to the database using PHP. I have utilized angular for this purpose, but only the last form field is getting inserted into the database. To address this, I attempted using arrays and loops to increment a ...

Ajax script causes error 403 when loading content while scrolling

Currently in the process of creating a blog using the HubSpot platform. The primary goal is to have blog posts load dynamically as users scroll down the page. I came across a script that claims to achieve this functionality and is designed specifically for ...