I'm working on a vuejs/(vuex) for state management/firebase project of posts.
So I have a firestore collection of posts (array of objects that have name id owner content and timestamp for creation ...) and when a user want to visit a single post it will redirect him to the route of the single post (..../view-post/postid).
All the posts are retrieved from the firestore using the getDocs method and it's stored on blogPosts variable...
I'm using a data and it's array that when the mounted lifecycle hook starts called currentBlog: null (when the component is mounted) i use that array and by filtering all the posts to the post id then start filling the data on the component using the array[0] like these:
async mounted() {
this.currentBlog = await this.blogPosts.filter((post) => {
return post.blogID == this.$route.params.blogid;
});
}
My html markup (template):
<section class="preview" v-if="currentBlog">
<h2>{{ currentBlog[0].blogTitle }}</h2>
<p>Posted on: <span>{{ dateFormat() }}</span> <span v-if="currentBlog[0].editTime">(Last edit:
{{ editFormat() }})</span></p>
<img class="blogCover" :src="currentBlog[0].blogCoverFileURL" :alt="currentBlog[0].blogCoverPhoto">
<div class="html-blog" v-html="currentBlog[0].blogHTML"></div>
<hr />
<div class="tags">
<h4>Tags:</h4>
<div class="tag" v-for="(tag,index) in currentBlog[0].blogTags" @click="filterPosts(tag)" :key="index">
{{ tag }}
</div>
</div>
<hr />
</section>
I used the first condition just to assure that the post is appearing when the it completes to filter but ...
Now I got the post, the problem that I face is when I refresh the page from the post and sometimes when I open the post directly, I get this error:
Uncaught (in promise) TypeError: this.currentBlog[0] is undefined
Any method to fix these or even any suggested other methods?