07-20-2023, 01:34 PM
I wrote a graphql query to get recent posts for a blog app in NextJs in other to display them as widgets
```
export const getRecentPosts = async () =\> {
const query = gql`
query MyQuery {
posts(orderBy: createdAt_ASC
last: 3 )
{title
featuredImage {url}
createdAt
slug
}
}
`;
const result = await request(graphAPI, query);
return result.posts;
};
```
but i keep getting a "Cannot read properties of undefined (reading 'document')" error
and it keeps displaying this error
[NextJs error]()
I imported the function into the component
```
function PostWidget({ categories, slug }) {
const [relatedPosts, setRelatedPosts] = useState([]);
useEffect(() => {
if (slug) {
getSimilarPosts(categories, slug).then((result) => {
setRelatedPosts(result);
});
} else {
getRecentPosts().then((result) => {
setRelatedPosts(result);
});
}
}, [slug]);
console.log(relatedPosts)
return (
<div className="bg-white shadow-lg rounded-lg p-8 mb-8">
<h3 className="text-xl mb-4 font-semibold border-b p-4">
{slug ? "Related posts" : "Recent posts"}
</h3>
{
relatedPosts.map((post) => (
<div key={post.title} className="flex items-center w-full mb-4">
<div className="w-16 flex-none">
<img
alt={post.title}
height="60px"
width="60px"
className="align-middle rounded-full"
src={post.featuredImage.url}
/>
</div>
</div>
))
}
</div>
)
}
```
but it gives an empty array when i console.log the related posts
```
export const getRecentPosts = async () =\> {
const query = gql`
query MyQuery {
posts(orderBy: createdAt_ASC
last: 3 )
{title
featuredImage {url}
createdAt
slug
}
}
`;
const result = await request(graphAPI, query);
return result.posts;
};
```
but i keep getting a "Cannot read properties of undefined (reading 'document')" error
and it keeps displaying this error
[NextJs error]()
I imported the function into the component
```
function PostWidget({ categories, slug }) {
const [relatedPosts, setRelatedPosts] = useState([]);
useEffect(() => {
if (slug) {
getSimilarPosts(categories, slug).then((result) => {
setRelatedPosts(result);
});
} else {
getRecentPosts().then((result) => {
setRelatedPosts(result);
});
}
}, [slug]);
console.log(relatedPosts)
return (
<div className="bg-white shadow-lg rounded-lg p-8 mb-8">
<h3 className="text-xl mb-4 font-semibold border-b p-4">
{slug ? "Related posts" : "Recent posts"}
</h3>
{
relatedPosts.map((post) => (
<div key={post.title} className="flex items-center w-full mb-4">
<div className="w-16 flex-none">
<img
alt={post.title}
height="60px"
width="60px"
className="align-middle rounded-full"
src={post.featuredImage.url}
/>
</div>
</div>
))
}
</div>
)
}
```
but it gives an empty array when i console.log the related posts