Vuex getters not displaying expected values in computed properties until entire page has finished loading

When working with computed properties using data fetched by the mapGetters function in my Vuex store, I always encounter the issue of getting an undefined value until the entire page or DOM is fully loaded.

For instance, I have an example of an isRegistered computed property that determines whether to hide or display certain buttons:

computed: {
      ...mapGetters(['solos', 'user']),
      isRegistered () {
        return this.solos.registered.indexOf(this.user._id) !== -1
      }
}

Below is the HTML code for buttons utilizing the isRegistered computed property:

<a href="#" class="register-button" v-if="!isRegistered">REGISTER NOW</a>
<a href="#" class="registered-button" v-if="isRegistered">REGISTERED</a>

I set the getters through an action called within the created hook:

created () {
      this.getTournament('solos').catch(err => {})
}

Here is the action responsible for setting the corresponding getters:

getTournament: ({commit}, type) => {
    return feathers.service('tournaments').find({
      query: {
        type: type,
        status: 'registering'
      }
    }).then(tourney => {
      commit(type.toUpperCase(), tourney.data[0])
    })
}

And here's the associated mutation and getter:

const mutations = {
  SOLOS (state, result) {
    state.solos = result;
  }
};
const getters = {
   solos (state) {
     return state.solos
   }
}

The problem arises when the value initially shows up as undefined before the PAGE/DOM is fully loaded, leading to the following error related to .indexOf:

TypeError: Cannot read property 'indexOf' of undefined

Currently, I've resorted to using an if statement within the computed property to check if the state data has been loaded yet:

isRegistered () {
  if (this.solos._id) return this.solos.registered.indexOf(this.user._id) !== -1
}

This workaround doesn't feel like the ideal approach. Is there something incorrect in my implementation?

Answer №1

The issue may stem from the lifecycle of Vue components.

During the created hook, the component's computed properties, watchers, and data are initialized synchronously, while the solos getter operates asynchronously within a promise. This asynchronous behavior can cause the lifecycle to move forward before the promise is fulfilled.

After the created hook completes, the watchers are set up, allowing any changes in data to reflect in the DOM. However, the solos will only be populated once the promise resolves. Therefore, at the start of the app initialization, the promise may not have been completed yet, but once it does, the data updates will be displayed.

To avoid this issue, one workaround is to use

v-if="solos.registered"
. I am currently exploring alternative solutions to address this challenge.

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

JavaScript and HTML with Node.js

Exploring the world of HTML, running smoothly with a static IP address 192.168.56.152 using apache on the host computer. <!DOCTYPE html> <html > <head> <title>OnlinePage</title> <meta charset="utf-8"& ...

Pressing the button will activate the Ctrl+z and Ctrl+y key commands

I have created two separate buttons for triggering actions equivalent to pressing Ctrl+z and Ctrl+y. I am attempting to make these actions occur with the click of a single button. However, when trying to set up the functionality to trigger Ctrl+z and Ctr ...

reconfigure keyboard shortcuts in web browser

In the popular web browser Google Chrome, users can quickly jump to the next tab by pressing CTRL + TAB. Is there a way to change or disable this shortcut? The provided code snippet does not seem to work as intended. $(document).keydown(function(e){ ...

What location is ideal for making API calls with React and Redux-thunk?

After extensively searching on StackOverflow.com and across the internet, I couldn't find a similar question. Therefore, please refrain from giving negative reputations if you happen to come across one as I truly need reputation at this point in my li ...

React is unable to identify the `activeKey` property on a DOM element

First and foremost, I am aware that there have been a few inquiries regarding this particular error, although stemming from differing sources. Below is the snippet of my code: <BrowserRouter> <React.Fragment> <Navbar className=& ...

There is an error in ReactJS: TypeError - _this.props.match is not defined

I am experiencing a TypeError in my console tab and I can't seem to figure out where the error is occurring in my source code. I am relatively new to ReactJS so any help in identifying what I'm doing wrong would be greatly appreciated. Thank you ...

Unlock exclusive design features from beyond a Component's borders (NativeScript + Vue)

My application is made up of: 6 different components within the component folder, 3 JavaScript files located in the library folder. Within component_1, there is a Layout with a reference called myLayout. One of the JS files, myLayoutHandler, manipulates ...

"Enscroll – revolutionizing the way we scroll in

I recently incorporated the "enscroll" javascript scroll bar into my webpage. You can find more information about it at <div id="enscroll_name"> <ul> <li id="p1">product1</li> <li id="p2">product2</li> ...

The disappearance of the "Event" Twitter Widget in the HTML inspector occurs when customized styles are applied

Currently, I am customizing the default Twitter widget that can be embedded on a website. While successfully injecting styles and making it work perfectly, I recently discovered that after injecting my styles, clicking on a Tweet no longer opens it in a ne ...

Having trouble integrating MaterialUI Datepicker, Dayjs, useFormik, and Yup

Currently, I am facing a recurring issue with the Material UI Date picker in conjunction with day js. The problem arises when I select a date on the calendar for the first time, it updates correctly in the text field but fails to work thereafter. Additiona ...

Updating items within an array in a MongoDB collection

I am facing a challenge where I have to pass an array of objects along with their IDs from the client-side code using JSON to an API endpoint handled by ExpressJS. My next task is to update existing database records with all the fields from these objects. ...

Struggling to understand the process of retrieving information from an Axios promise

For my current project, I've been experimenting with using Axios to retrieve JSON data from a json-server to simulate a database environment. While I can successfully display the retrieved data within the .then() block of the Axios function, I'm ...

Vue-jest was unable to gather coverage data from a Vue file

Greetings! As a newcomer to Vue and Jest, I recently integrated Jest into an existing Vue project. My goal is to obtain test coverage results from .js and .vue files. However, I have encountered some difficulties in the process. Upon attempting to run ...

I'm attempting to create a button using html, but I'm puzzled as to why it's not functioning as expected

I've been working on creating a button that, when pressed, generates a new div string based on the node.innerHTML code. For some reason, my code doesn't seem to be functioning properly and I'm not sure why. Here's the HTML: <input ...

Tips for securely implementing JSON web tokens when integrating an external application with the WordPress REST API

I have a query regarding JWT. Let's consider this situation. A -> wordpress site with wp rest api enabled; B -> External application (for example, a simple javascript/jQuery app) Suppose I want to make a post request or create a new post on the wor ...

Designing a dropdown menu within displaytag

I am currently utilizing displaytag to present tabular data, but I aspire to design a user interface akin to "kayak.com" where clicking on a row reveals additional details without refreshing the page. Here is an example scenario before clicking the Detail ...

Problem with MongoDB - increasing number of connections

I have encountered an issue with my current approach to connecting to MongoDB. The method I am using is outlined below: import { Db, MongoClient } from "mongodb"; let cachedConnection: { client: MongoClient; db: Db } | null = null; export asyn ...

What is the Ideal Location for Storing the JSON file within an Angular Project?

I am trying to access the JSON file I have created, but encountering an issue with the source code that is reading the JSON file located in the node_modules directory. Despite placing the JSON file in a shared directory (at the same level as src), I keep r ...

The success method in the observable is failing to trigger

Could someone explain why the () success method is not triggering? It seems to be working fine when using forkjoin(). Shouldn't the success method fire every time, similar to a final method in a try-catch block? Note: Inline comments should also be c ...

Picture disappearing following the refresh of an AJAX iframe

Currently, I am developing a profile system where the user's profile is displayed in an iframe that reloads when the form submit button is clicked. The content updates successfully upon reloading, but there is an issue with images not displaying after ...