Experiencing a mysterious error in Vuex with undefined values while using a getter in a computed property

I've encountered an issue on my Vue.js website where the data is rendering correctly, but I keep receiving an undefined error in the console. The error seems to be related to an axios call I'm making in App.vue to fetch data from my CMS:

In App.vue:

async created() {

const strapiData = await getStrapiData();

// Update Vuex
this.$store.dispatch('setStrapi', strapiData);

}

Then in one of my components, I'm using a getter to access the data stored in Vuex:

In About.vue:

computed: {
    aboutData() {
        return this.$store.getters.strapiData.data.about
    }
}

I then reference this data in my template code:

<img :src="aboutData.photo.name">

Although everything is rendering properly, I'm seeing this error in the console:

TypeError: Cannot read property 'photo' of undefined
at a.r (About.vue?3e5e:1)

I suspect that the issue might be related to the order in which my components are being created. I'm importing all child components into App.vue and rendering them there, but it seems like the child components are being created before the created lifecycle hook of App.vue:

In App.vue script:

components: {
'app-about' : About,

In App.vue template:

<template>
  <div id="app">
    <app-about></app-about>
  </div>
</template>

If anyone has any insights on what might be causing this issue, I would greatly appreciate your help. Thank you!

Answer №1

At the creation of the component, the axios call is not yet resolved, resulting in aboutData being undefined. Once the call is resolved, aboutData is rendered. The process of it being undefined and then rendered are 2 sequential events. By using v-if, the initial event is eliminated as aboutData is only called after the axios call has resolved and the data is available.

A common practice is to have a property called loading with a default value of false. This property is then set to true when the axios call starts and set back to false when the call is resolved. Within the template, a "Loading Message" can be displayed while loading is true.

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

Using the `setTimeout` function to swap components

As I work on implementing a setTimeout method, the goal is to trigger an event after a .5 second delay when one of the three buttons (drip, french press, Aeropress) is pressed. This event will replace {{ShowText}} with {{ShowText2}}, which will display &ap ...

Guide to implementing Swiper.js (version 8+) within Nuxt.js (2.15.8)

Initially, I attempted to implement the code shown on the official Swiper.js website for Vue 3 demo: <template> <swiper :effect="'coverflow'" :grabCursor="true" :centeredSlides="true" :slidesPerView="'auto' ...

JavaScript: Targeting elements by their tag name within a designated container

When working with PHP, it is possible to use the getElementsByTagName method on any DOM object. However, this concept does not seem to exist in JavaScript. For example, if we have a specific node stored in the variable detailsNode, attempting to use detai ...

Is it possible for me to generate values using PHP that can be easily read by JavaScript?

I'm currently building a website and I am facing some challenges when trying to incorporate JavaScript for real-time calculations. Here are my issues: Is there a more efficient way to avoid manually typing out the code for each level up to 90, lik ...

What is the process of assigning data, in JSON format, from an HTML form to a variable?

I have the coding below in my abc.html file, which converts form data to JSON format: <body> <form enctype='application/json' method="POST" name="myForm"> <p><label>Company:</label> <input name=& ...

What is the best way to arrange the keys within a nested object in JavaScript?

Question: { "foo": "bar", "bar": "baz", "baz" : { "nestedKey": "foo" } } In order to sign this request using the Hmac512 algorithm, I must first stringify the object. I am concerned that if the key order is not preserved, the generated signature on the ...

Struggling with integrating jQuery append into Backbone.js

Having trouble using jQuery.append() and backbonejs. Currently, when attempting to append, nothing happens (except the jQuery object is returned in the immediate window) and the count remains at 0. Manually adding the element has not been successful. I als ...

Align the reposition button with the pagination in the datatables

I am looking to adjust the placement of my buttons. The buttons in question are for comparison, saving layout, and printing. I would like them to be inline with the pagination, as I am using datatables here. <table id="sparepart_id" cellspacing="0" ...

creating a function that sends two separate fetch requests with a pause in between each request

Currently, I am working with 2 endpoints. The first one requires a "post" request, and upon receiving the response, it should provide me with an ID that is used in the URL of the second endpoint. To ensure that I can obtain this ID before proceeding with ...

What is the best way to rearrange an array in React?

I need help with manipulating an array of strings displayed in a list. Each string should have the ability to move up or down within the array. For example: const array = ["hello", "world", "cool"] moveUp("world", 1) // (moveUp: value:string, index: nu ...

Prevent the selection of a dropdown option in AngularJS once it has already

var demoApp = angular.module('myApp', []); demoApp.controller('QaController', function($scope, $http) { $scope.loopData = [{}, {}]; $scope.questions = { model: null, availableOptions: [ {id: '1& ...

The webpage displays the element as <span class="icon">&#xe80d;</span> instead of rendering it properly

In my ReactJS project, I have created a component called Menu1item: class Menu1item extends React.Component{ render(){ return ( <div> {this.props.glyph}{this.props.value} </div> ) ...

Function being called by Intersection Observer at an inappropriate moment

After running the page, the intersection observer behaves exactly as desired. However, upon reloading the page, I am automatically taken back to the top of the page (which is expected). Strangely though, when the viewport interacts with the target elemen ...

The animation for enter active in Vue3 transition-group is not working, but the one for leave is functioning properly

I attempted to animate the addition and deletion of elements within a v-for loop. While looking for solutions, I noticed that most answers focused on class name changes in Vue3 compared to Vue2. However, I am confident that my issue is not related to clas ...

Microsoft Edge browser incorrectly calculates range.endOffset value

This particular problem is specific to the Microsoft Edge browser. I am attempting to apply a CSS style to a selected word using Range API's, but I am encountering an issue with the range.endOffset functionality in Edge. Below is the code snippet I am ...

VueJS throws an error indicating that the object cannot be extended

I have encountered an issue while trying to update the promo object by adding a new field called colspan. Unfortunately, I am getting this error: uncaught (in promise) TypeError: Cannot add property colspan, object is not extensible at eval (eval at ...

Utilizing components in next.js

I am attempting to transform the following class <div className={`banner-row marquee ${playMarquee && "animate"}`}> into a format compatible with next.js. I am struggling to find a solution. ...

Error: Async API Call Triggering Invalid Hook Invocation

When working with my functional component, I encountered an issue while trying to implement a react hook like useMemo or useEffect. It seems that the error may be caused by the asynchronous nature of the API call. In the service file: export const getData ...

The custom created THREE.Curve is not rendering correctly

Following advice from this solution, I have implemented a linearly interpolated curve in the code below: THREE.Linear3 = THREE.Curve.create( function ( points, label /* array of Vector3 */) { this.points = (points == undefined) ? [] : points; ...

Learn the process of updating an Xero invoice seamlessly with the xero-Node integration

After successfully integrating Xero with my app for accounting and billing purposes, I am now looking to update a previous invoice that was created in the past on Xero. Is there a solution available for this? Any suggestions would be greatly appreciated. ...