How to set data within VueJS lifecycle hook
javascript, vue-component, vue.js, vuejs2
Solution
You are setting the data asynchronously so it doesn't exist when the object is first mounted. When you try to access `forecastData.currently.summary` the `currently` property is undefined, which results in your error.
Use a `v-if` to avoid the error.
<h2 v-if="forecastData.currently">{{forecastData.currently.summary}}</h2>
Alternatively, define a null summary in your initialization.
data () {
return {
forecastData: {
summary: null
}
}
},
Problem
I am attempting to use the `created` lifecycle hook to set a data property on my component. Below is my single-file component. I'm currently seeing `"TypeError: Cannot read property 'summary' of undefined"` in the console when running this code. This tells me that the template is working with `forecastData` as the empty object declared in the `data` property rather than the populated object from `created`. When I remove the `data` property entirely I see `TypeError: Cannot read property 'currently' of undefined`. Clearly, I'm missing something basic here. ``` <template> <div> <p> <router-link to="/">Back to places</router-link> </p> <h2>{{forecastData.currently.summary}}</h2> <router-link :to="{ name: 'forecast' }">Forecast</router-link> <router-link :to="{ name: 'alerts' }">Alerts</router-link> <hr> <router-view></router-view> </div> </template> <script> export default { name: 'CurrentWeather', data () { return { forecastData: {} } }, created: function () { this.$http.get('/api/forecast/boston').then((response) => { this.forecastData = response.data; }, (err) => { console.log(err) }); } } </script> <style scoped> </style> ```