Reputation: 2877
My child component receives a prop called config
, which is an object whose properties I display in my template or pass as props to other components:
<template>
<section class="container">
<h2 class="title">
{{ config.section_header }}
</h2>
<custom-button
v-for="(button, i) in config.section_buttons"
:key="i"
v-bind="button"
/>
</section>
</template>
The parent view component itself gets the config
object from the store.
In my parent view component:
created () {
this.initializeStore()
},
computed: {
...mapState({
config: state => state.template?.section ?? null
})
}
The store is populated asynchronously via an Axios
call:
export const actions = {
initializeStore ({ state, commit }, data) {
this.$axios.get('/path/to/api/endpoint')
.then((res) => {
// state object gets populated
})
}
}
Because the config
prop is defined only after the store API call resolves, my component throws undefined
error everywhere I'm trying to display parts of it. For example:
Cannot read property 'section_buttons' of null
How to solve this problem?
Upvotes: 1
Views: 41
Reputation: 1
In initial rendering your data has not been available yet, so you've to add a conditional rendering everywhere you get that error :
<template>
<section class="container">
<h2 class="title" v-if="config">
{{ config.section_header }}
</h2>
<template v-if="config && config.section_buttons">
<custom-button
v-for="(button, i) in config.section_buttons"
:key="i"
v-bind="button"
/>
</template>
</section>
</template>
Upvotes: 2