WoJ
WoJ

Reputation: 29987

How to avoid providing a dummy Vue data structure during initialization?

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?

Upvotes: 2

Views: 514

Answers (1)

LiranC
LiranC

Reputation: 2480

  • 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> 

Upvotes: 6

Related Questions