Recently, I've completed a setup of a Next.js project in conjunction with a headless Wordpress CMS. To display content, my posts and pages utilize custom Gutenberg blocks. The following plugins have been integrated into the CMS:
- WP GraphQl
- WP GraphQL Gutenberg
- WPGraphQL for Advanced Custom Fields
- ACF Pro
Within the Advanced Custom Fields (ACF) plugin, an 'Image' Block has been configured with a text field and an image field.
In my codebase, there is a query present in the lib/api.js
file as shown below (14 represents the ID for the current image selected, which may vary):
export async function getImageById() {
const data = await fetchAPI(
`
query GetImageDetails($id: Int = 14) {
mediaItems(where: {id: $id}) {
nodes {
mediaItemUrl
mediaItemId
}
}
}
`
)
return data;
}
The folder structure is organized as follows:
- - lib
- - components
- - Blocks
- - universalImage.js
- - Pages
- - blog
- - index.js
- - [slug].js
- - blog
- - Public
When the query is invoked within the index.js
file, it successfully retrieves information about 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, attempting to call the query in the [slug].js
file results in an empty array being returned:
Code snippet from [slug].js
:
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
}
}
}
Being new to Next.js and React, I might be overlooking something obvious. Any assistance would be greatly appreciated as progress on the project is currently stalled. Feel free to request more information if needed.
The FetchAPI function used is as follows:
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;
}