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 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 :src="currentBlog[0].blogCoverFileURL" :alt="currentBlog[0].blogCoverPhoto">
<div v-html="currentBlog[0].blogHTML"></div>
<hr />
<div >
<h4>Tags:</h4>
<div 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?
CodePudding user response:
My first thought is where do you have the function running that is getting the blogPosts with getDocs. What is likely happening is the function that fetched the blog posts can run and finish when you visit the homepage of your application, but when you try to view a post directly that function has not run yet.
I'd recommend setting a v-if on your that only resolves to true once the blog post data is fetched.
An alternative could be for you to check your Vuex store for the blog posts within the view blog post component, and if they are not there then you can just fetch them from the said component. This is likely not favorable as your entire app relies on the blog posts' data I assume.
Here is an example
I'd also note that you don't have to await the filter function, and if you just want to get a single blog post it may be helpful to create a getter that does that in your Vuex store.
CodePudding user response:
Well the only solution i found was taking the id of the blog from the route (this.$route.params.blogid) and using it to retrieve one single data from the firebase directly!