I've recently set up a Next.js project along with a headless Wordpress CMS. My posts & pages are using custom Gutenberg blocks to pull content through. I've set up the following plugins on the CMS:
WP GraphQl, WP GraphQL Gutenberg, WPGraphQL for Advanced Custom Fields and ACF Pro.
Within ACF I have set up an 'Image' Block, which has a text field and an image field.
Within my code, I have a query in my lib/api.js
file like below (14 is the ID for the current image selected - this will change):
export async function getImageById() {
const data = await fetchAPI(
`
query GetImageDetails($id: Int = 14) {
mediaItems(where: {id: $id}) {
nodes {
mediaItemUrl
mediaItemId
}
}
}
`
)
return data;
}
My folder structure is as follows.
If I call the query in my index.js
file, it returns info on the media image:
export default function Home({posts, first, imgs}) {
console.log(imgs)
return(
<div>
//all my content
</div>
)
}
export async function getStaticProps() {
const images = await getImageById();
const jsonI = await images;
return {
props: {
imgs: jsonI
}
}
}
However if I try to call it in my [slug].js
file I get back an empty array
[slug].js
code
export default function Post(postData, imgs) {
console.log(imgs)
return(
<div>
//all my content
</div>
)
}
export async function getStaticPaths() {
const allPosts = await getAllPostsWithSlug();
return {
paths: allPosts.edges.map(({node}) => `/blog/${node.slug}`) || [],
fallback: true
};
}
export async function getStaticProps({ params }) {
const data = await getPost(params.slug);
const imgs = await getImageById();
return {
props: {
postData: data.post,
imgs
}
}
}
I am new to Next.js and React so maybe I'm missing something obvious, however any help would be appreciated as I can't progress much further in the project.
Also if you need any more info please let me know.
FetchAPI function is:
async function fetchAPI(query, { variables } = {}) {
// Set up some headers to tell the fetch call
// that this is an application/json type
const headers = { 'Content-Type': 'application/json' };
// build out the fetch() call using the API_URL
// environment variable pulled in at the start
// Note the merging of the query and variables
const res = await fetch(API_URL, {
method: 'POST',
headers,
body: JSON.stringify({ query, variables })
});
// error handling work
const json = await res.json();
if (json.errors) {
console.log(json.errors);
console.log('error details', query, variables);
throw new Error('Failed to fetch API');
}
return json.data;
}
Issue was that I was missing a set of brackets {}
.
export default function Post({ postData, imgs }) { ... }
Thanks to @juliomalves!