2

In my Vue-driven HTML I have the line

<span>Last updated on {{incident.LastUpdate[0].date}}</span>

data in the Vue instance is defined as

data: {
    incident: {}
}

In the course of the execution, incident is asynchonously loaded but during the initial page load I see

[Vue warn]: Error in render: "TypeError: Cannot read property '0' of undefined"
(...)
TypeError: Cannot read property '0' of undefined

This is understandable because the incident contents are not available yet. When they are abvailable, the page is displayed correctly. The error is therefore predictibe and temporary so I could just forget it.

I wanted however to silence it and initialized incident with some dummy data

data: {
        incident: {
            LastUpdate: [
                {
                    date: null
                }
            ]
        },
    },

The error is now gone but I feel that this is awkward way to solve it. It can also become cumbersome if there is a more data to initialize.

My question: what is the correct way to handle this problem in Vue? Dummy data as in my fix?

2
  • I seen the same behavior in some other frameworks, even if just for a very short time but does really get noticeable when pages are loading slow.. Commented Oct 17, 2017 at 16:23
  • 1
    I usually wrap the content that is wainting some async data with a <span v-if="incident != null">, or another flag, that determines whether show or not some data Commented Oct 17, 2017 at 16:37

1 Answer 1

6
  • Declare an empty array. it will help other developers to understand the structure of your data upfront
  • Keep your Markup logic-less as possible. use Computed method to retrieve the first value, with error handling.

see the code:

<template>
    <div>
        Last updated on {{lastUpdatedTime}}
    </div>
</template>
<script>
export default {
    data(){
        return {
            incident: {
                lastUpdate:[]
            }
        }
    },
    computed: {
        lastUpdatedTime () {
            if (this.incident.LastUpdate.length === 0) return '' // think about a default please :)
            return this.incident.LastUpdate[0].date
        }
    }

}
</script> 
Sign up to request clarification or add additional context in comments.

1 Comment

These are good points, thanks. Especially the second one is a neat fix (and overall a good approach indeed).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.