'TypeError: Cannot read properties of null in the template tag
I'm getting a "TypeError: Cannot read properties of null" error in my Vue/Laravel application. I get data from API. I can access data in the script tag for example in mounted method but in the template I can't access the data.
<template>
<article class="hentry blog-post single-post single-post-v3">
<router-link :to="'/kategori/'+post.category.slug" class="post-category bg-primary">{{post.category.title}}</router-link>
<h1 class="post-title">{{post.title}}</h1>
...
</template>
<script>
export default {
components: {
FeaturedPosts,
Comments
},
async beforeRouteEnter(to, from, next) {
const returned = (await axios.get(route("api.post", to.params.slug))).data.response
next(vm => {
vm.post = returned.post;
vm.comments = (returned.comments != undefined) ? returned.comments.data : null;
vm.commentsPagination = (returned.comments != undefined) ? returned.comments : null;
});
},
data() {
return {
post: null,
comments: null,
commentsPagination: null,
};
},
}
</script>
It gives "Uncaught (in promise) TypeError: Cannot read properties of null (reading 'category')". I can access post.category in mounted() method but in the template I can't.
Solution 1:[1]
next(vm => ...) callback is triggered after the instance is created, the state that is initialized there shouldn't be relied on because initial rendering occurs with uninitialized state.
It should be either:
return {
post: [],
...
Or:
<article v-if="post" ...>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Estus Flask |
