On my Nuxt site, I have developed the homepage and the blog page. When navigating to a specific blog post, the page is to call the store and pass the slug to fetch the data using async and then display the information. Sometimes an error of content is undefined unless the page is reloaded.
My current setup is:
- Nuxt 3 SSR (3.0.0-rc.9)
- Pinia
- Tailwindcss
This is my post page:
<template>
<div class='grid grid-cols-6 gap -2'>
{{ post.content }}
</div>
</template>
<script setup lang="ts">
import { useRoute } from 'vue-router';
import { usePostStore } from '../../../../stores/post';
import { ref } from 'vue';
const postStore = usePostStore()
const route = useRoute()
const slug = route.params.slug
const post = ref({})
postStore.getPostBySlug(slug)
post.value = await postStore.currentPost[0]
definePageMeta({
layout: "posts",
})
useHead(
{
title: post.title
}
)
</script>
This is my store:
import { defineStore } from 'pinia';
export const usePostStore = defineStore('post-store', () => {
const posts = ref([]);
const pressReleases = ref([]);
const news = ref([]);
const currentPost = ref([]);
async function getPressReleases() {
const { data, error } = await useAsyncGql({
operation: 'getPostByCategory',
variables: { category: 'Press Release' },
});
pressReleases.value = data._rawValue.post;
}
async function getNews() {
const { data, error } = await useAsyncGql({
operation: 'getPostByCategory',
variables: { category: 'News' },
});
news.value = data._rawValue.post;
}
async function getAllPosts() {
const { data, error } = await useAsyncGql({
operation: 'getAllPosts',
});
posts.value = data._rawValue.post;
}
async function getPostBySlug(slug) {
const { data, error } = await useAsyncGql({
operation: 'getPostBySlug',
variables: { slug: slug },
});
currentPost.value = data._rawValue.post;
}
// function filterPostByCategory(categoryName) {
// return posts.filter((post) => {
// return post.category.name === categoryName;
// });
// }
// const filterByCategory = computed((categoryName) => {
// return posts.filter((post) => {
// return post.category.name === categoryName;
// });
// });
return {
posts,
currentPost,
pressReleases,
news,
getPressReleases,
getNews,
getPostBySlug,
getAllPosts,
// filterPostByCategory,
// filterByCategory,
};
});
I would think this would work but instead, I get this error: 500 error: Cannot read properties of undefined (reading 'content')
CodePudding user response:
You've got an await
in the wrong spot. Instead of:
postStore.getPostBySlug(slug)
post.value = await postStore.currentPost[0]
it should be
await postStore.getPostBySlug(slug)
post.value = postStore.currentPost[0]
Otherwise, postStore.currentPost[0]
is undefined