The graphQL query is working http://trialtest1.local/graphql?query={%20posts%20{%20nodes%20{%20slug%20title%20}%20}}
But when I ask for posts in next.js it shows undefined. Can anyone see what Im doing wrong?
import Link from 'next/link'
export default function Home( {posts}){
console.log({posts})
return(
<div>
<h1>Hello From The Home Page!</h1>
{
posts?.nodes?.map(post => {
return(
<ul key={post.slug}>
<li>
<Link href={`/posts/${post.slug}`}>{post.title}</Link>
</li>
</ul>
)
})
}
</div>
)
}
export async function getInitialProps(){
const res = await fetch('http://trialtest1.local/graphql', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
query: `
query HomePageQuery {
posts {
nodes {
slug
title
}
}
}
`,
})
})
const json = await res.json()
return {
props: {
posts: json.data.posts,
},
}
}
In your Next.js application, the issue might be related to how you're accessing the GraphQL response data. When using 'getInitialProps', the GraphQL response is usually in the 'data' object. Here's a modification to your code to access the posts correctly:
export async function getInitialProps() {
const res = await fetch('http://trialtest1.local/graphql', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
query: `
query HomePageQuery {
posts {
nodes {
slug
title
}
}
}
`,
}),
});
const json = await res.json();
return {
props: {
posts: json.data.posts.nodes, // Access nodes directly
},
};
}
In your component, 'posts' should now contain an array of post objects. Ensure that you're accessing the correct data structure in the 'Home' component using 'posts.nodes.map' to iterate over each post. Also, check your console logs to ensure the data is being fetched and passed correctly to the component.