"Encountering an issue with the Vuex store value not being properly assigned

Recently, I've been facing an issue with my store where I'm encountering a null value intermittently on certain values. If someone could provide some guidance and explain what might be causing this inconsistency, I would greatly appreciate it. Here's the scenario: sometimes my store.getters.getApiKey returns an empty string "", while other times it doesn't.

For example, in the Vue component below, the first reference to

{{this.$store.getters.getApiKey}}
is not null:

{{this.$store.getters.getApiKey}}

However, within the mounted section of the component, even after setting store.getters.getHostUrl, store.getters.getApiKey continues to return an empty string "".

Here are some specifics:
the Component.vue

<template>
  <div class="countryCodes">
    <p>ApiKey :  {{this.$store.getters.getApiKey}}</p>
    <p>CountryCode Data is {{ page }}</p>
    <div class="CountryCodes">
      <tr v-for="ccdata in content_list" v-bind:key="ccdata.guid">
        <td>{{ ccdata.guid }}</td>
        <td>{{ ccdata.name }}</td>
        <td>{{ ccdata.code }}</td>
      </tr>
    </div>
  </div>
</template>

import axios from "axios";
import store from "@/store";

export default {
  name: 'CountryCodes',
  data () {
    return {
      page: "",
      content_list: []
    }
  },
  mounted () {
   axios({ method: "GET", "url": store.getters.getHostUrl + " 
"/api/"+store.getters.getApiKey+"/countryCodes" }).then(result => {
      this.page = result.data.page;
      this.content_list = result.data.contents;
    }, error => {
      console.error(error);
    });
  },
  methods: {
  }
}
</script>

The configuration of my store (store.js) is as follows...

import Vuex from "vuex";
import Vue from 'vue';

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        apiKey: "",
        hostUrl:""
    },
    mutations: {
        SET_APIKEY(state, value) { state.apiKey = value;   },
        SET_HOST_URL(state, value) {state.hostUrl = value; }
    },
    getters: {
        getApiKey(state) {  return state.apiKey; },
        getHostUrl(state) {  return state.hostUrl; }
    }
})

Lastly, in my main.js file, I commit the data changes to the store...

import Vue from 'vue'
import App from './App.vue'
import router from './router/index.js'
import store from './store.js'

new Vue({
  el: '#app',
  render: h => h(App),
  router,
  store,
  mounted: function() {
    console.log(this.$route.query)
    store.commit('SET_APIKEY',  this.$route.query.api)
    store.commit("SET_HOST_URL", location.origin.toString())
  }
})

I'm also experiencing a similar problem when trying to construct an HTTP service, as the store appears to be returning a null value for the apikey. Any ideas on what might be causing this inconsistency?

Answer №1

Typically, the mounted hook of a child component is triggered before the mounted hook of its parent component.

https://i.sstatic.net/0fghe.png

Referenced from Vue Parent and Child lifecycle hooks

If you log both mounted hooks, you can observe the sequence of execution (although it's unclear why your store.getters.getHostUrl is not being set).

Therefore, you should utilize a watcher to execute your code only after the store has been populated with values.

Example snippet:

...
  computed: { // Alternatively, utilize other getters
    url () {
      if (!store.getters.getHostUrl || !store.getters.getApiKey) return
      return `${store.getters.getHostUrl}/api/${store.getters.getApiKey}/countryCodes`
    }
  },
  watch: {
    url (value) {
      ...
    }
  }
...

CodeSandbox

Answer №2

After much deliberation, I have found two different solutions to this problem. Many thanks to all who provided input.

  1. I decided to switch my mounted function in the main.js file to created based on the diagram provided and a helpful article I came across.

  2. Another suggestion was to add "await store.getters.getApiKey".

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

Utilizing JSON File as an Array in a Node.JS Environment

I'm struggling with converting a .json file into an array object using NodeJS, Here's the JSON content: { "cat": { "nani": "meow" }, "dog": { "nani": "woof" } } index.js: const array = require('../../data/use ...

Assistance required for JavaScript with Image and Hyperlinks

In the provided code snippet, I have included a javascript onclick function to the image tag. After clicking the image and then going back, the page remains on the current page rather than returning to the original page. Is there a way to prevent this beha ...

Struggling to retrieve the data from a RESTful API?

I'm currently learning how to fetch an API in javascript and I'm encountering some difficulties in extracting specific parts of the response body. My goal is to store the setup and punchline of a joke in variables for later use. Here is the code ...

Animate hovering over a specific element within a group of similar elements using jQuery

Hi there! I recently started exploring Js and jQuery, and I was able to create a cool width change animation on a div when hovering over another. However, I ran into an issue when trying to implement this with multiple sets of similar divs. Whenever I hove ...

Adjust the JavaScript variable upon pressing the "c" key

I'm trying to figure out how I can toggle the value of variable x in JavaScript when the key "c" is pressed. Specifically, I want x to change from 0 to 1 when "c" is pressed and revert back to 0 when it's released. I have already defined and name ...

Generating interactive elements in VUE is key

I am unsure about how to dynamically create components without using the <component :is=''> tag. I would like to insert a component into the DOM through JavaScript. Similar to how you would add a new modal in jQuery with $("body").append(" ...

Avoiding Scroll Reset on Browser Navigation with Delayed Transition

I've recently implemented a delay in my router configuration on my website. However, I've noticed that when I try to navigate using the browser's back and forward buttons, it first jumps to the top of the page because of the delay set with { ...

`How can I update a textbox's value using JQuery Ajax?`

Currently in the process of implementing an ajax call to update the value of a textbox: <div id="PNIncrementDiv" style="position:absolute; left: 730px; top: 15px; width: 350px;" class=""> <input id="TBIncrementTextBox" class="textbox" type="te ...

Is my utilization of the Promise feature correct?

I am currently using node to fetch data from a URL with the help of cheerio. const request=require('request'); const cheerio=require('cheerio'); const Promise = require('promise'); The function getDataParms(parm1, parm2) ret ...

The VueJS component from a third-party source is not located in the node_modules directory

Utilizing vue-cli version 3 for a fresh vuejs project (I've been dedicating ample time to learning vuejs, but this marks my initial attempt at integrating a third-party component). I'm aiming to incorporate a visually appealing grid component. Th ...

Animating Text Changes with JavaScript and jQuery

In my HTML, I have an input type="text" element and I want to attach an event handler that triggers when the text is changed. The issue arises because this input's value is dynamically updated by another JavaScript function, causing the event handler ...

What is the best way to leverage local storage/memory to save information for my text-based RPG game?

Currently, I am in the process of creating a text-based RPG on Codecademy. However, I am facing a challenge when it comes to implementing a save/load system using JavaScript/HTML. My idea is to create a system where players can type "save" into a prompt, ...

What are the steps to enable ajax communication with a database for posting, retrieving, and removing data?

Is there a way to utilize ajax for posting, deleting, and getting data from a database? I am looking to post content and then be able to delete it through the following link: (this is part of an assignment) However, I must use /ajax/addrecord.php and /a ...

A guide on utilizing Socket.io to efficiently transfer data to a specific client within a designated chat room

Can someone please advise on the correct way to send data to a specific client in a specific room using socket io? The code snippet I have been trying is: I am using the following command: socket.to(socket.id).emit('change', {data}) However, i ...

Steps to assign a default value to the KeyboardTimePicker

I am utilizing the KeyboardTimePicker component from material ui to fetch a time of service such as "10:20". How can I make this time ("10:20") the default selection? When attempting to set this time, I am receiving an error stating " ...

How can I access the most up-to-date state value in an event listener within a React element?

Here is the code I am working with: var C = () => { var [s, setS] = useState(0) var dRef = useRef<HTMLDivElement>() useMount(() => { setShortcut("ArrowDown", () => { setS(s+1) }) }) return ...

How can I pick out paragraphs that don't end with a period and eliminate dashes using jQuery or JavaScript?

Here are the paragraphs I need assistance with: <p>This is the initial paragraph.</p> <p>This is the second one</p> <p>The third paragraph comes next.</p> <p>Last, but not least</p> The second and fourth pa ...

The custom service is failing to load, in the simplest terms possible

After creating a dataService.j that contains the following: angular.module('dataService', []) .service('gameDataService', function() { var _gameData = { loggedIn: "false", gameJoined:"false", tableFu ...

Dynamically submitting a form generated within the AJAX success callback in CodeIgniter

After creating a form dynamically within the success function of an AJAX call, I expected it to submit like a normal form in CodeIgniter. However, upon clicking the submit button, the form data is not being picked up by the appropriate controller. The ori ...

Vue-resource is returning a Promise object

How do I access the response data in an Ajax call? When I log response.text(), it displays a PromiseObj. Console PromiseObj context: undefined promise: Promise {status: "resolved", result: ")]}',↵{\"Result\":\"SUCCESS\",&bs ...