Vue Component Rendering Before Vuex Data is Ready

I am facing a challenge with my Vue2 component that depends on Vuex to fetch the currently selected node (infoNode) and display its data to the user. In my beforeCreate function, Axios is used to retrieve the top level nodes and set the 'infoNode' as the first node in the process:

  async beforeCreate(){
    const info = await axios.get('/ajax/company-info')
    if(info.data){
      this.$store.dispatch("setCompanyInfo", info.data)
    }

// Function to retrieve top level node
    const topLevel = await axios.get('/ajax/get-root-contents')
    if(topLevel.data){
      this.$store.dispatch("loadTopLevel", topLevel.data)
    }
  },

The Vuex function below sets the infoNode

loadTopLevel(state,node){
      state.infoNode = node
    },

In the following code snippet, I attempt to access the infoNode data and display an icon from an array of valid icons

<v-icon size="6em" v-if="fileIcons[infoNode.data.filetype]">{{ fileIcons[infoNode.data.filetype] }}</v-icon>

Now, within my component, I have a computed property that retrieves this infoNode from the store for rendering. The problem arises when the frontend throws an error stating 'e.infoNode.Data' is undefined.

This error occurs before the request is completed. Once the request finishes, the frontend successfully displays the updated infoNode data.

I have attempted several variations of beforeCreate (async and non), as well as created/mounted cycles, but haven't been able to resolve the issue. Is there a way to ensure the data is set in the store before the component attempts to access it?

Answer №1

BeforeCreate() in your situation is asynchronous, causing the component to render before the data is set in the store. You are currently showing v-icon if there is a specific entry in fileIcons (based on infoNode.data.filetype), but at that point infoNode may be undefined or infoNode.data may be undefined.

In using v-if, it is important to verify that infoNode is not undefined and contains the entry you are looking for.

You can do something like this:

computed: {
  hasEntry() {
    if(infoNode && ('data' in infoNode)) return true

    return false
  }
}

//template
<v-icon size="6em" v-if="hasEntry">{{ fileIcons[infoNode.data.filetype] }}</v-icon>

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

The scroll header remains fixed in size despite being responsive

I've been struggling to resize a fixed header when the page is scrolled. Unfortunately, I'm having trouble getting the header to adjust its size as the scrolling happens. $(document).scroll(function() { navbarScroll(); }); function navbarSc ...

Can you explain the difference between CDN and ESM builds in vue.js?

According to the Vue.js documentation, there are differences in syntax depending on whether you are using the CDN or ESM build of Vue.js. What is the significance of having two different builds and how does it result in a difference in usage syntax? Infor ...

Replacing an existing pie chart with a new one using JavaScript

I created pie charts using chartjs V2.6.0, and everything was working fine until I encountered an issue. Whenever I input new data into the same chart, it keeps displaying the previous data when hovering over. I attempted to fix this by using the $('# ...

Looking for a custom textured circle in three.js?

Is there a way to create a circle with a texture on one side in three.js without using sprites? I was considering using THREE.CylinderGeometry, but I'm unsure of where to add the "materials" in the new THREE.CylinderGeometry(...) section. Any suggest ...

Are you ensuring compliance with licensing in your Webpack bundles?

Can webpack be used to verify license compliance? I'm looking for a way to ensure that the license headers from all modules built by webpack are included in the final output file. How can we confirm this is happening? Furthermore, I am also intereste ...

Tap on the image to enlarge

I have a question regarding using thumbnails from Bootstrap. I am trying to create functionality where when I click on a thumbnail, the picture with its original sizes appears and then disappears when clicked anywhere else on the page. Below is an exampl ...

Step-by-step guide on inserting a div element or hotspot within a 360 panorama image using three.js

As I work on creating a virtual tour using 360 images, I am looking to include hotspots or div elements within the image that can be clicked. How can I store data in my database from the event values such as angle value, event.clientX, and event.clientY wh ...

Displaying an element outside with reduced opacity using fabric js and controls placed above overlay

The property controlsAboveOverlay in Fabric.js is a boolean that, when set to true, will display the controls (borders, corners, etc.) of an object above the overlay image. The overlay image is an image that can be placed on top of the canvas. Currently, ...

"Trouble in Transmitting: Node.js Fails to

As a beginner in programming, I am currently following a tutorial to enhance my skills. I've encountered a roadblock and I can't seem to successfully post new entries using the code. I'm struggling to identify what I might be missing here. ...

Utilizing React Material UI for form validation with error handling and informative helper text

I recently created a form in which I needed to validate the inputs. During my research, I came across the material UI library that has an attribute called error boolean, and another attribute called helperText for the TextField input of the form. However ...

Can a script be dynamically loaded into a div while accessing local variables?

Consider the scenario where you have two files: test.html <div id="stuff"></div> <button onclick="doStuff()">Magic</button> <script> var foo = new function() { this.bar = function() { return "THE MAGIC!"; }; ...

navigate to a new page in vue with node.js

As I continue to expand my knowledge in JavaScript, Vue, and Node.js, I encountered a specific issue that I need help with. My goal is to redirect the Vue page after logging in using Node.js. Below you'll find the code snippets for my Vue setup and sc ...

The collapsible list feature that includes the use of plus and minus signs is malfunctioning

Below is the script that I wrote to address this issue, but for some reason the + and - swapping is not functioning correctly. $('.showCheckbox').click(function(e) { var dynamicBox = $(this).attr('val'); var collapseSign = $(th ...

Learn the best practices for integrating the options API with the Composition API in Vue3

Using vue3 and vite2 Below is a simple code snippet. The expected behavior is that when the button is clicked, the reactive 'msg' variable should change. It works as expected in development using Vite, but after building for production (Vi ...

Tips for removing a previous file from an 'input type' in HTML5 FileReader

Here is a file input with an associated function: <img id="uploadPreview"> <div id="changeImage">Change</div> <div id="customImage"> <input type="file" id="myfile" multiple style="display:none" onchange="PreviewImage();" / ...

Having difficulty passing the new state value using props in ReactJS

I am facing an issue with sending state values from parent to child components. Initially, the state value is empty but after making an API call, the state value gets updated. However, the props in my child component are still stuck with the initial empty ...

Ensuring Compliance with GDPR through Cookie Consent Logic

Since the introduction of GDPR, I find myself in need of clarity on the steps to take both server-side and client-side to ensure compliance. Apologies for the plethora of questions. I currently have a first-party cookie that is used to store a session coo ...

Having trouble with installing Vue CLI?

I am encountering issues while attempting to set up VueJS. I am currently utilizing Bash on Ubuntu on Windows node -v v15.12.0 npm -v 7.6.3 Initially, I attempted the following: npm install -g @vue/cli However, this resulted in various warnings and ...

Unable to alter state from the onClick event of a dialog button

In the process of developing a Next.js app, I encountered an interesting challenge within one of the components involving a DropdownMenu that triggers a DialogAlert (both powered by Shadcn components). The issue arises when attempting to manage the dialog& ...

Rendering a Vue component: displaying raw HTML entities without escaping them

Is there a way in Vue 2 to prevent the escape of HTML entities and have them rendered as normal text? When dealing with a tag, I know I can nest another createElement, but that's not the case here. Vue.component('my-component', { render ...